From 08ee639fb731ffd3a74087587db5a78d09d6f9b0 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 31 May 2024 10:56:25 +0000 Subject: [PATCH 1/2] feat: A new field `metadata` is added to message `.google.cloud.networkservices.v1.LbTrafficExtension` feat: A new field `metadata` is added to message `.google.cloud.networkservices.v1.LbRouteExtension` docs: update the comments for dep resources PiperOrigin-RevId: 638948066 Source-Link: https://github.com/googleapis/googleapis/commit/2244fe42081794c9cc8c8b1a4519365116960620 Source-Link: https://github.com/googleapis/googleapis-gen/commit/c5ce68285306098ce797532bd02121160757f7b2 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW5ldHdvcmstc2VydmljZXMvLk93bEJvdC55YW1sIiwiaCI6ImM1Y2U2ODI4NTMwNjA5OGNlNzk3NTMyYmQwMjEyMTE2MDc1N2Y3YjIifQ== --- .../v1/.coveragerc | 13 + .../google-cloud-network-services/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../docs/network_services_v1/dep_service.rst | 10 + .../network_services_v1/network_services.rst | 10 + .../v1/docs/network_services_v1/services_.rst | 7 + .../v1/docs/network_services_v1/types_.rst | 6 + .../google/cloud/network_services/__init__.py | 181 + .../cloud/network_services/gapic_version.py | 16 + .../v1/google/cloud/network_services/py.typed | 2 + .../cloud/network_services_v1/__init__.py | 182 + .../network_services_v1/gapic_metadata.json | 782 + .../network_services_v1/gapic_version.py | 16 + .../google/cloud/network_services_v1/py.typed | 2 + .../network_services_v1/services/__init__.py | 15 + .../services/dep_service/__init__.py | 22 + .../services/dep_service/async_client.py | 2148 ++ .../services/dep_service/client.py | 2498 ++ .../services/dep_service/pagers.py | 260 + .../dep_service/transports/__init__.py | 38 + .../services/dep_service/transports/base.py | 370 + .../services/dep_service/transports/grpc.py | 718 + .../dep_service/transports/grpc_asyncio.py | 773 + .../services/dep_service/transports/rest.py | 2226 ++ .../services/network_services/__init__.py | 22 + .../services/network_services/async_client.py | 5791 +++ .../services/network_services/client.py | 6202 +++ .../services/network_services/pagers.py | 993 + .../network_services/transports/__init__.py | 38 + .../network_services/transports/base.py | 791 + .../network_services/transports/grpc.py | 1487 + .../transports/grpc_asyncio.py | 1687 + .../network_services/transports/rest.py | 5574 +++ .../network_services_v1/types/__init__.py | 188 + .../cloud/network_services_v1/types/common.py | 227 + .../cloud/network_services_v1/types/dep.py | 945 + .../types/endpoint_policy.py | 317 + .../network_services_v1/types/gateway.py | 305 + .../network_services_v1/types/grpc_route.py | 719 + .../network_services_v1/types/http_route.py | 1125 + .../cloud/network_services_v1/types/mesh.py | 255 + .../types/network_services.py | 26 + .../types/service_binding.py | 215 + .../network_services_v1/types/tcp_route.py | 405 + .../network_services_v1/types/tls_route.py | 366 + .../google-cloud-network-services/v1/mypy.ini | 3 + .../v1/noxfile.py | 253 + ...service_create_lb_route_extension_async.py | 67 + ..._service_create_lb_route_extension_sync.py | 67 + ...rvice_create_lb_traffic_extension_async.py | 67 + ...ervice_create_lb_traffic_extension_sync.py | 67 + ...service_delete_lb_route_extension_async.py | 56 + ..._service_delete_lb_route_extension_sync.py | 56 + ...rvice_delete_lb_traffic_extension_async.py | 56 + ...ervice_delete_lb_traffic_extension_sync.py | 56 + ...ep_service_get_lb_route_extension_async.py | 52 + ...dep_service_get_lb_route_extension_sync.py | 52 + ..._service_get_lb_traffic_extension_async.py | 52 + ...p_service_get_lb_traffic_extension_sync.py | 52 + ..._service_list_lb_route_extensions_async.py | 53 + ...p_service_list_lb_route_extensions_sync.py | 53 + ...ervice_list_lb_traffic_extensions_async.py | 53 + ...service_list_lb_traffic_extensions_sync.py | 53 + ...service_update_lb_route_extension_async.py | 65 + ..._service_update_lb_route_extension_sync.py | 65 + ...rvice_update_lb_traffic_extension_async.py | 65 + ...ervice_update_lb_traffic_extension_sync.py | 65 + ...k_services_create_endpoint_policy_async.py | 62 + ...rk_services_create_endpoint_policy_sync.py | 62 + ...d_network_services_create_gateway_async.py | 63 + ...ed_network_services_create_gateway_sync.py | 63 + ...etwork_services_create_grpc_route_async.py | 62 + ...network_services_create_grpc_route_sync.py | 62 + ...etwork_services_create_http_route_async.py | 62 + ...network_services_create_http_route_sync.py | 62 + ...ated_network_services_create_mesh_async.py | 61 + ...rated_network_services_create_mesh_sync.py | 61 + ...k_services_create_service_binding_async.py | 62 + ...rk_services_create_service_binding_sync.py | 62 + ...network_services_create_tcp_route_async.py | 61 + ..._network_services_create_tcp_route_sync.py | 61 + ...network_services_create_tls_route_async.py | 62 + ..._network_services_create_tls_route_sync.py | 62 + ...k_services_delete_endpoint_policy_async.py | 56 + ...rk_services_delete_endpoint_policy_sync.py | 56 + ...d_network_services_delete_gateway_async.py | 56 + ...ed_network_services_delete_gateway_sync.py | 56 + ...etwork_services_delete_grpc_route_async.py | 56 + ...network_services_delete_grpc_route_sync.py | 56 + ...etwork_services_delete_http_route_async.py | 56 + ...network_services_delete_http_route_sync.py | 56 + ...ated_network_services_delete_mesh_async.py | 56 + ...rated_network_services_delete_mesh_sync.py | 56 + ...k_services_delete_service_binding_async.py | 56 + ...rk_services_delete_service_binding_sync.py | 56 + ...network_services_delete_tcp_route_async.py | 56 + ..._network_services_delete_tcp_route_sync.py | 56 + ...network_services_delete_tls_route_async.py | 56 + ..._network_services_delete_tls_route_sync.py | 56 + ...work_services_get_endpoint_policy_async.py | 52 + ...twork_services_get_endpoint_policy_sync.py | 52 + ...ated_network_services_get_gateway_async.py | 52 + ...rated_network_services_get_gateway_sync.py | 52 + ...d_network_services_get_grpc_route_async.py | 52 + ...ed_network_services_get_grpc_route_sync.py | 52 + ...d_network_services_get_http_route_async.py | 52 + ...ed_network_services_get_http_route_sync.py | 52 + ...nerated_network_services_get_mesh_async.py | 52 + ...enerated_network_services_get_mesh_sync.py | 52 + ...work_services_get_service_binding_async.py | 52 + ...twork_services_get_service_binding_sync.py | 52 + ...ed_network_services_get_tcp_route_async.py | 52 + ...ted_network_services_get_tcp_route_sync.py | 52 + ...ed_network_services_get_tls_route_async.py | 52 + ...ted_network_services_get_tls_route_sync.py | 52 + ...k_services_list_endpoint_policies_async.py | 53 + ...rk_services_list_endpoint_policies_sync.py | 53 + ...ed_network_services_list_gateways_async.py | 53 + ...ted_network_services_list_gateways_sync.py | 53 + ...network_services_list_grpc_routes_async.py | 53 + ..._network_services_list_grpc_routes_sync.py | 53 + ...network_services_list_http_routes_async.py | 53 + ..._network_services_list_http_routes_sync.py | 53 + ...ated_network_services_list_meshes_async.py | 53 + ...rated_network_services_list_meshes_sync.py | 53 + ...rk_services_list_service_bindings_async.py | 53 + ...ork_services_list_service_bindings_sync.py | 53 + ..._network_services_list_tcp_routes_async.py | 53 + ...d_network_services_list_tcp_routes_sync.py | 53 + ..._network_services_list_tls_routes_async.py | 53 + ...d_network_services_list_tls_routes_sync.py | 53 + ...k_services_update_endpoint_policy_async.py | 60 + ...rk_services_update_endpoint_policy_sync.py | 60 + ...d_network_services_update_gateway_async.py | 61 + ...ed_network_services_update_gateway_sync.py | 61 + ...etwork_services_update_grpc_route_async.py | 60 + ...network_services_update_grpc_route_sync.py | 60 + ...etwork_services_update_http_route_async.py | 60 + ...network_services_update_http_route_sync.py | 60 + ...ated_network_services_update_mesh_async.py | 59 + ...rated_network_services_update_mesh_sync.py | 59 + ...network_services_update_tcp_route_async.py | 59 + ..._network_services_update_tcp_route_sync.py | 59 + ...network_services_update_tls_route_async.py | 60 + ..._network_services_update_tls_route_sync.py | 60 + ...adata_google.cloud.networkservices.v1.json | 8136 ++++ .../fixup_network_services_v1_keywords.py | 224 + .../google-cloud-network-services/v1/setup.py | 94 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.7.txt | 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_services_v1/__init__.py | 16 + .../network_services_v1/test_dep_service.py | 10386 +++++ .../test_network_services.py | 31441 ++++++++++++++++ 164 files changed, 94666 insertions(+) create mode 100644 owl-bot-staging/google-cloud-network-services/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-services/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-services/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-services/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json create mode 100644 owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py create mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/.coveragerc b/owl-bot-staging/google-cloud-network-services/v1/.coveragerc new file mode 100644 index 000000000000..778e27d73587 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_services/__init__.py + google/cloud/network_services/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-services/v1/.flake8 b/owl-bot-staging/google-cloud-network-services/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in new file mode 100644 index 000000000000..75e280b90bde --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/network_services *.py +recursive-include google/cloud/network_services_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/README.rst b/owl-bot-staging/google-cloud-network-services/v1/README.rst new file mode 100644 index 000000000000..afbddfa3288a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Network Services 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 Services API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py new file mode 100644 index 000000000000..dc71e2abe004 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-services" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-network-services-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-services.tex", + u"google-cloud-network-services 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-services", + u"Google Cloud Network Services 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-services", + u"google-cloud-network-services Documentation", + author, + "google-cloud-network-services", + "GAPIC library for Google Cloud Network Services API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst new file mode 100644 index 000000000000..5975c3816b2b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_services_v1/services + network_services_v1/types diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst new file mode 100644 index 000000000000..b6844727e4f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst @@ -0,0 +1,10 @@ +DepService +---------------------------- + +.. automodule:: google.cloud.network_services_v1.services.dep_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_services_v1.services.dep_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst new file mode 100644 index 000000000000..29ec7184b84c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst @@ -0,0 +1,10 @@ +NetworkServices +--------------------------------- + +.. automodule:: google.cloud.network_services_v1.services.network_services + :members: + :inherited-members: + +.. automodule:: google.cloud.network_services_v1.services.network_services.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst new file mode 100644 index 000000000000..ca8a37c10d65 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Network Services v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + dep_service + network_services diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst new file mode 100644 index 000000000000..5706e60c91b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Services v1 API +============================================== + +.. automodule:: google.cloud.network_services_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py new file mode 100644 index 000000000000..49d70c891e5c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_services import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_services_v1.services.dep_service.client import DepServiceClient +from google.cloud.network_services_v1.services.dep_service.async_client import DepServiceAsyncClient +from google.cloud.network_services_v1.services.network_services.client import NetworkServicesClient +from google.cloud.network_services_v1.services.network_services.async_client import NetworkServicesAsyncClient + +from google.cloud.network_services_v1.types.common import EndpointMatcher +from google.cloud.network_services_v1.types.common import OperationMetadata +from google.cloud.network_services_v1.types.common import TrafficPortSelector +from google.cloud.network_services_v1.types.dep import CreateLbRouteExtensionRequest +from google.cloud.network_services_v1.types.dep import CreateLbTrafficExtensionRequest +from google.cloud.network_services_v1.types.dep import DeleteLbRouteExtensionRequest +from google.cloud.network_services_v1.types.dep import DeleteLbTrafficExtensionRequest +from google.cloud.network_services_v1.types.dep import ExtensionChain +from google.cloud.network_services_v1.types.dep import GetLbRouteExtensionRequest +from google.cloud.network_services_v1.types.dep import GetLbTrafficExtensionRequest +from google.cloud.network_services_v1.types.dep import LbRouteExtension +from google.cloud.network_services_v1.types.dep import LbTrafficExtension +from google.cloud.network_services_v1.types.dep import ListLbRouteExtensionsRequest +from google.cloud.network_services_v1.types.dep import ListLbRouteExtensionsResponse +from google.cloud.network_services_v1.types.dep import ListLbTrafficExtensionsRequest +from google.cloud.network_services_v1.types.dep import ListLbTrafficExtensionsResponse +from google.cloud.network_services_v1.types.dep import UpdateLbRouteExtensionRequest +from google.cloud.network_services_v1.types.dep import UpdateLbTrafficExtensionRequest +from google.cloud.network_services_v1.types.dep import EventType +from google.cloud.network_services_v1.types.dep import LoadBalancingScheme +from google.cloud.network_services_v1.types.endpoint_policy import CreateEndpointPolicyRequest +from google.cloud.network_services_v1.types.endpoint_policy import DeleteEndpointPolicyRequest +from google.cloud.network_services_v1.types.endpoint_policy import EndpointPolicy +from google.cloud.network_services_v1.types.endpoint_policy import GetEndpointPolicyRequest +from google.cloud.network_services_v1.types.endpoint_policy import ListEndpointPoliciesRequest +from google.cloud.network_services_v1.types.endpoint_policy import ListEndpointPoliciesResponse +from google.cloud.network_services_v1.types.endpoint_policy import UpdateEndpointPolicyRequest +from google.cloud.network_services_v1.types.gateway import CreateGatewayRequest +from google.cloud.network_services_v1.types.gateway import DeleteGatewayRequest +from google.cloud.network_services_v1.types.gateway import Gateway +from google.cloud.network_services_v1.types.gateway import GetGatewayRequest +from google.cloud.network_services_v1.types.gateway import ListGatewaysRequest +from google.cloud.network_services_v1.types.gateway import ListGatewaysResponse +from google.cloud.network_services_v1.types.gateway import UpdateGatewayRequest +from google.cloud.network_services_v1.types.grpc_route import CreateGrpcRouteRequest +from google.cloud.network_services_v1.types.grpc_route import DeleteGrpcRouteRequest +from google.cloud.network_services_v1.types.grpc_route import GetGrpcRouteRequest +from google.cloud.network_services_v1.types.grpc_route import GrpcRoute +from google.cloud.network_services_v1.types.grpc_route import ListGrpcRoutesRequest +from google.cloud.network_services_v1.types.grpc_route import ListGrpcRoutesResponse +from google.cloud.network_services_v1.types.grpc_route import UpdateGrpcRouteRequest +from google.cloud.network_services_v1.types.http_route import CreateHttpRouteRequest +from google.cloud.network_services_v1.types.http_route import DeleteHttpRouteRequest +from google.cloud.network_services_v1.types.http_route import GetHttpRouteRequest +from google.cloud.network_services_v1.types.http_route import HttpRoute +from google.cloud.network_services_v1.types.http_route import ListHttpRoutesRequest +from google.cloud.network_services_v1.types.http_route import ListHttpRoutesResponse +from google.cloud.network_services_v1.types.http_route import UpdateHttpRouteRequest +from google.cloud.network_services_v1.types.mesh import CreateMeshRequest +from google.cloud.network_services_v1.types.mesh import DeleteMeshRequest +from google.cloud.network_services_v1.types.mesh import GetMeshRequest +from google.cloud.network_services_v1.types.mesh import ListMeshesRequest +from google.cloud.network_services_v1.types.mesh import ListMeshesResponse +from google.cloud.network_services_v1.types.mesh import Mesh +from google.cloud.network_services_v1.types.mesh import UpdateMeshRequest +from google.cloud.network_services_v1.types.service_binding import CreateServiceBindingRequest +from google.cloud.network_services_v1.types.service_binding import DeleteServiceBindingRequest +from google.cloud.network_services_v1.types.service_binding import GetServiceBindingRequest +from google.cloud.network_services_v1.types.service_binding import ListServiceBindingsRequest +from google.cloud.network_services_v1.types.service_binding import ListServiceBindingsResponse +from google.cloud.network_services_v1.types.service_binding import ServiceBinding +from google.cloud.network_services_v1.types.tcp_route import CreateTcpRouteRequest +from google.cloud.network_services_v1.types.tcp_route import DeleteTcpRouteRequest +from google.cloud.network_services_v1.types.tcp_route import GetTcpRouteRequest +from google.cloud.network_services_v1.types.tcp_route import ListTcpRoutesRequest +from google.cloud.network_services_v1.types.tcp_route import ListTcpRoutesResponse +from google.cloud.network_services_v1.types.tcp_route import TcpRoute +from google.cloud.network_services_v1.types.tcp_route import UpdateTcpRouteRequest +from google.cloud.network_services_v1.types.tls_route import CreateTlsRouteRequest +from google.cloud.network_services_v1.types.tls_route import DeleteTlsRouteRequest +from google.cloud.network_services_v1.types.tls_route import GetTlsRouteRequest +from google.cloud.network_services_v1.types.tls_route import ListTlsRoutesRequest +from google.cloud.network_services_v1.types.tls_route import ListTlsRoutesResponse +from google.cloud.network_services_v1.types.tls_route import TlsRoute +from google.cloud.network_services_v1.types.tls_route import UpdateTlsRouteRequest + +__all__ = ('DepServiceClient', + 'DepServiceAsyncClient', + 'NetworkServicesClient', + 'NetworkServicesAsyncClient', + 'EndpointMatcher', + 'OperationMetadata', + 'TrafficPortSelector', + 'CreateLbRouteExtensionRequest', + 'CreateLbTrafficExtensionRequest', + 'DeleteLbRouteExtensionRequest', + 'DeleteLbTrafficExtensionRequest', + 'ExtensionChain', + 'GetLbRouteExtensionRequest', + 'GetLbTrafficExtensionRequest', + 'LbRouteExtension', + 'LbTrafficExtension', + 'ListLbRouteExtensionsRequest', + 'ListLbRouteExtensionsResponse', + 'ListLbTrafficExtensionsRequest', + 'ListLbTrafficExtensionsResponse', + 'UpdateLbRouteExtensionRequest', + 'UpdateLbTrafficExtensionRequest', + 'EventType', + 'LoadBalancingScheme', + 'CreateEndpointPolicyRequest', + 'DeleteEndpointPolicyRequest', + 'EndpointPolicy', + 'GetEndpointPolicyRequest', + 'ListEndpointPoliciesRequest', + 'ListEndpointPoliciesResponse', + 'UpdateEndpointPolicyRequest', + 'CreateGatewayRequest', + 'DeleteGatewayRequest', + 'Gateway', + 'GetGatewayRequest', + 'ListGatewaysRequest', + 'ListGatewaysResponse', + 'UpdateGatewayRequest', + 'CreateGrpcRouteRequest', + 'DeleteGrpcRouteRequest', + 'GetGrpcRouteRequest', + 'GrpcRoute', + 'ListGrpcRoutesRequest', + 'ListGrpcRoutesResponse', + 'UpdateGrpcRouteRequest', + 'CreateHttpRouteRequest', + 'DeleteHttpRouteRequest', + 'GetHttpRouteRequest', + 'HttpRoute', + 'ListHttpRoutesRequest', + 'ListHttpRoutesResponse', + 'UpdateHttpRouteRequest', + 'CreateMeshRequest', + 'DeleteMeshRequest', + 'GetMeshRequest', + 'ListMeshesRequest', + 'ListMeshesResponse', + 'Mesh', + 'UpdateMeshRequest', + 'CreateServiceBindingRequest', + 'DeleteServiceBindingRequest', + 'GetServiceBindingRequest', + 'ListServiceBindingsRequest', + 'ListServiceBindingsResponse', + 'ServiceBinding', + 'CreateTcpRouteRequest', + 'DeleteTcpRouteRequest', + 'GetTcpRouteRequest', + 'ListTcpRoutesRequest', + 'ListTcpRoutesResponse', + 'TcpRoute', + 'UpdateTcpRouteRequest', + 'CreateTlsRouteRequest', + 'DeleteTlsRouteRequest', + 'GetTlsRouteRequest', + 'ListTlsRoutesRequest', + 'ListTlsRoutesResponse', + 'TlsRoute', + 'UpdateTlsRouteRequest', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/google/cloud/network_services/py.typed b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed new file mode 100644 index 000000000000..dfe9bf70b7d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-services package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py new file mode 100644 index 000000000000..3eff2a66dbaa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_services_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.dep_service import DepServiceClient +from .services.dep_service import DepServiceAsyncClient +from .services.network_services import NetworkServicesClient +from .services.network_services import NetworkServicesAsyncClient + +from .types.common import EndpointMatcher +from .types.common import OperationMetadata +from .types.common import TrafficPortSelector +from .types.dep import CreateLbRouteExtensionRequest +from .types.dep import CreateLbTrafficExtensionRequest +from .types.dep import DeleteLbRouteExtensionRequest +from .types.dep import DeleteLbTrafficExtensionRequest +from .types.dep import ExtensionChain +from .types.dep import GetLbRouteExtensionRequest +from .types.dep import GetLbTrafficExtensionRequest +from .types.dep import LbRouteExtension +from .types.dep import LbTrafficExtension +from .types.dep import ListLbRouteExtensionsRequest +from .types.dep import ListLbRouteExtensionsResponse +from .types.dep import ListLbTrafficExtensionsRequest +from .types.dep import ListLbTrafficExtensionsResponse +from .types.dep import UpdateLbRouteExtensionRequest +from .types.dep import UpdateLbTrafficExtensionRequest +from .types.dep import EventType +from .types.dep import LoadBalancingScheme +from .types.endpoint_policy import CreateEndpointPolicyRequest +from .types.endpoint_policy import DeleteEndpointPolicyRequest +from .types.endpoint_policy import EndpointPolicy +from .types.endpoint_policy import GetEndpointPolicyRequest +from .types.endpoint_policy import ListEndpointPoliciesRequest +from .types.endpoint_policy import ListEndpointPoliciesResponse +from .types.endpoint_policy import UpdateEndpointPolicyRequest +from .types.gateway import CreateGatewayRequest +from .types.gateway import DeleteGatewayRequest +from .types.gateway import Gateway +from .types.gateway import GetGatewayRequest +from .types.gateway import ListGatewaysRequest +from .types.gateway import ListGatewaysResponse +from .types.gateway import UpdateGatewayRequest +from .types.grpc_route import CreateGrpcRouteRequest +from .types.grpc_route import DeleteGrpcRouteRequest +from .types.grpc_route import GetGrpcRouteRequest +from .types.grpc_route import GrpcRoute +from .types.grpc_route import ListGrpcRoutesRequest +from .types.grpc_route import ListGrpcRoutesResponse +from .types.grpc_route import UpdateGrpcRouteRequest +from .types.http_route import CreateHttpRouteRequest +from .types.http_route import DeleteHttpRouteRequest +from .types.http_route import GetHttpRouteRequest +from .types.http_route import HttpRoute +from .types.http_route import ListHttpRoutesRequest +from .types.http_route import ListHttpRoutesResponse +from .types.http_route import UpdateHttpRouteRequest +from .types.mesh import CreateMeshRequest +from .types.mesh import DeleteMeshRequest +from .types.mesh import GetMeshRequest +from .types.mesh import ListMeshesRequest +from .types.mesh import ListMeshesResponse +from .types.mesh import Mesh +from .types.mesh import UpdateMeshRequest +from .types.service_binding import CreateServiceBindingRequest +from .types.service_binding import DeleteServiceBindingRequest +from .types.service_binding import GetServiceBindingRequest +from .types.service_binding import ListServiceBindingsRequest +from .types.service_binding import ListServiceBindingsResponse +from .types.service_binding import ServiceBinding +from .types.tcp_route import CreateTcpRouteRequest +from .types.tcp_route import DeleteTcpRouteRequest +from .types.tcp_route import GetTcpRouteRequest +from .types.tcp_route import ListTcpRoutesRequest +from .types.tcp_route import ListTcpRoutesResponse +from .types.tcp_route import TcpRoute +from .types.tcp_route import UpdateTcpRouteRequest +from .types.tls_route import CreateTlsRouteRequest +from .types.tls_route import DeleteTlsRouteRequest +from .types.tls_route import GetTlsRouteRequest +from .types.tls_route import ListTlsRoutesRequest +from .types.tls_route import ListTlsRoutesResponse +from .types.tls_route import TlsRoute +from .types.tls_route import UpdateTlsRouteRequest + +__all__ = ( + 'DepServiceAsyncClient', + 'NetworkServicesAsyncClient', +'CreateEndpointPolicyRequest', +'CreateGatewayRequest', +'CreateGrpcRouteRequest', +'CreateHttpRouteRequest', +'CreateLbRouteExtensionRequest', +'CreateLbTrafficExtensionRequest', +'CreateMeshRequest', +'CreateServiceBindingRequest', +'CreateTcpRouteRequest', +'CreateTlsRouteRequest', +'DeleteEndpointPolicyRequest', +'DeleteGatewayRequest', +'DeleteGrpcRouteRequest', +'DeleteHttpRouteRequest', +'DeleteLbRouteExtensionRequest', +'DeleteLbTrafficExtensionRequest', +'DeleteMeshRequest', +'DeleteServiceBindingRequest', +'DeleteTcpRouteRequest', +'DeleteTlsRouteRequest', +'DepServiceClient', +'EndpointMatcher', +'EndpointPolicy', +'EventType', +'ExtensionChain', +'Gateway', +'GetEndpointPolicyRequest', +'GetGatewayRequest', +'GetGrpcRouteRequest', +'GetHttpRouteRequest', +'GetLbRouteExtensionRequest', +'GetLbTrafficExtensionRequest', +'GetMeshRequest', +'GetServiceBindingRequest', +'GetTcpRouteRequest', +'GetTlsRouteRequest', +'GrpcRoute', +'HttpRoute', +'LbRouteExtension', +'LbTrafficExtension', +'ListEndpointPoliciesRequest', +'ListEndpointPoliciesResponse', +'ListGatewaysRequest', +'ListGatewaysResponse', +'ListGrpcRoutesRequest', +'ListGrpcRoutesResponse', +'ListHttpRoutesRequest', +'ListHttpRoutesResponse', +'ListLbRouteExtensionsRequest', +'ListLbRouteExtensionsResponse', +'ListLbTrafficExtensionsRequest', +'ListLbTrafficExtensionsResponse', +'ListMeshesRequest', +'ListMeshesResponse', +'ListServiceBindingsRequest', +'ListServiceBindingsResponse', +'ListTcpRoutesRequest', +'ListTcpRoutesResponse', +'ListTlsRoutesRequest', +'ListTlsRoutesResponse', +'LoadBalancingScheme', +'Mesh', +'NetworkServicesClient', +'OperationMetadata', +'ServiceBinding', +'TcpRoute', +'TlsRoute', +'TrafficPortSelector', +'UpdateEndpointPolicyRequest', +'UpdateGatewayRequest', +'UpdateGrpcRouteRequest', +'UpdateHttpRouteRequest', +'UpdateLbRouteExtensionRequest', +'UpdateLbTrafficExtensionRequest', +'UpdateMeshRequest', +'UpdateTcpRouteRequest', +'UpdateTlsRouteRequest', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json new file mode 100644 index 000000000000..0c8a6247dfc9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json @@ -0,0 +1,782 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_services_v1", + "protoPackage": "google.cloud.networkservices.v1", + "schema": "1.0", + "services": { + "DepService": { + "clients": { + "grpc": { + "libraryClient": "DepServiceClient", + "rpcs": { + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DepServiceAsyncClient", + "rpcs": { + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + }, + "rest": { + "libraryClient": "DepServiceClient", + "rpcs": { + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + } + } + }, + "NetworkServices": { + "clients": { + "grpc": { + "libraryClient": "NetworkServicesClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "CreateGateway": { + "methods": [ + "create_gateway" + ] + }, + "CreateGrpcRoute": { + "methods": [ + "create_grpc_route" + ] + }, + "CreateHttpRoute": { + "methods": [ + "create_http_route" + ] + }, + "CreateMesh": { + "methods": [ + "create_mesh" + ] + }, + "CreateServiceBinding": { + "methods": [ + "create_service_binding" + ] + }, + "CreateTcpRoute": { + "methods": [ + "create_tcp_route" + ] + }, + "CreateTlsRoute": { + "methods": [ + "create_tls_route" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "DeleteGateway": { + "methods": [ + "delete_gateway" + ] + }, + "DeleteGrpcRoute": { + "methods": [ + "delete_grpc_route" + ] + }, + "DeleteHttpRoute": { + "methods": [ + "delete_http_route" + ] + }, + "DeleteMesh": { + "methods": [ + "delete_mesh" + ] + }, + "DeleteServiceBinding": { + "methods": [ + "delete_service_binding" + ] + }, + "DeleteTcpRoute": { + "methods": [ + "delete_tcp_route" + ] + }, + "DeleteTlsRoute": { + "methods": [ + "delete_tls_route" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "GetGateway": { + "methods": [ + "get_gateway" + ] + }, + "GetGrpcRoute": { + "methods": [ + "get_grpc_route" + ] + }, + "GetHttpRoute": { + "methods": [ + "get_http_route" + ] + }, + "GetMesh": { + "methods": [ + "get_mesh" + ] + }, + "GetServiceBinding": { + "methods": [ + "get_service_binding" + ] + }, + "GetTcpRoute": { + "methods": [ + "get_tcp_route" + ] + }, + "GetTlsRoute": { + "methods": [ + "get_tls_route" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "ListGateways": { + "methods": [ + "list_gateways" + ] + }, + "ListGrpcRoutes": { + "methods": [ + "list_grpc_routes" + ] + }, + "ListHttpRoutes": { + "methods": [ + "list_http_routes" + ] + }, + "ListMeshes": { + "methods": [ + "list_meshes" + ] + }, + "ListServiceBindings": { + "methods": [ + "list_service_bindings" + ] + }, + "ListTcpRoutes": { + "methods": [ + "list_tcp_routes" + ] + }, + "ListTlsRoutes": { + "methods": [ + "list_tls_routes" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + }, + "UpdateGateway": { + "methods": [ + "update_gateway" + ] + }, + "UpdateGrpcRoute": { + "methods": [ + "update_grpc_route" + ] + }, + "UpdateHttpRoute": { + "methods": [ + "update_http_route" + ] + }, + "UpdateMesh": { + "methods": [ + "update_mesh" + ] + }, + "UpdateTcpRoute": { + "methods": [ + "update_tcp_route" + ] + }, + "UpdateTlsRoute": { + "methods": [ + "update_tls_route" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NetworkServicesAsyncClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "CreateGateway": { + "methods": [ + "create_gateway" + ] + }, + "CreateGrpcRoute": { + "methods": [ + "create_grpc_route" + ] + }, + "CreateHttpRoute": { + "methods": [ + "create_http_route" + ] + }, + "CreateMesh": { + "methods": [ + "create_mesh" + ] + }, + "CreateServiceBinding": { + "methods": [ + "create_service_binding" + ] + }, + "CreateTcpRoute": { + "methods": [ + "create_tcp_route" + ] + }, + "CreateTlsRoute": { + "methods": [ + "create_tls_route" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "DeleteGateway": { + "methods": [ + "delete_gateway" + ] + }, + "DeleteGrpcRoute": { + "methods": [ + "delete_grpc_route" + ] + }, + "DeleteHttpRoute": { + "methods": [ + "delete_http_route" + ] + }, + "DeleteMesh": { + "methods": [ + "delete_mesh" + ] + }, + "DeleteServiceBinding": { + "methods": [ + "delete_service_binding" + ] + }, + "DeleteTcpRoute": { + "methods": [ + "delete_tcp_route" + ] + }, + "DeleteTlsRoute": { + "methods": [ + "delete_tls_route" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "GetGateway": { + "methods": [ + "get_gateway" + ] + }, + "GetGrpcRoute": { + "methods": [ + "get_grpc_route" + ] + }, + "GetHttpRoute": { + "methods": [ + "get_http_route" + ] + }, + "GetMesh": { + "methods": [ + "get_mesh" + ] + }, + "GetServiceBinding": { + "methods": [ + "get_service_binding" + ] + }, + "GetTcpRoute": { + "methods": [ + "get_tcp_route" + ] + }, + "GetTlsRoute": { + "methods": [ + "get_tls_route" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "ListGateways": { + "methods": [ + "list_gateways" + ] + }, + "ListGrpcRoutes": { + "methods": [ + "list_grpc_routes" + ] + }, + "ListHttpRoutes": { + "methods": [ + "list_http_routes" + ] + }, + "ListMeshes": { + "methods": [ + "list_meshes" + ] + }, + "ListServiceBindings": { + "methods": [ + "list_service_bindings" + ] + }, + "ListTcpRoutes": { + "methods": [ + "list_tcp_routes" + ] + }, + "ListTlsRoutes": { + "methods": [ + "list_tls_routes" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + }, + "UpdateGateway": { + "methods": [ + "update_gateway" + ] + }, + "UpdateGrpcRoute": { + "methods": [ + "update_grpc_route" + ] + }, + "UpdateHttpRoute": { + "methods": [ + "update_http_route" + ] + }, + "UpdateMesh": { + "methods": [ + "update_mesh" + ] + }, + "UpdateTcpRoute": { + "methods": [ + "update_tcp_route" + ] + }, + "UpdateTlsRoute": { + "methods": [ + "update_tls_route" + ] + } + } + }, + "rest": { + "libraryClient": "NetworkServicesClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "CreateGateway": { + "methods": [ + "create_gateway" + ] + }, + "CreateGrpcRoute": { + "methods": [ + "create_grpc_route" + ] + }, + "CreateHttpRoute": { + "methods": [ + "create_http_route" + ] + }, + "CreateMesh": { + "methods": [ + "create_mesh" + ] + }, + "CreateServiceBinding": { + "methods": [ + "create_service_binding" + ] + }, + "CreateTcpRoute": { + "methods": [ + "create_tcp_route" + ] + }, + "CreateTlsRoute": { + "methods": [ + "create_tls_route" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "DeleteGateway": { + "methods": [ + "delete_gateway" + ] + }, + "DeleteGrpcRoute": { + "methods": [ + "delete_grpc_route" + ] + }, + "DeleteHttpRoute": { + "methods": [ + "delete_http_route" + ] + }, + "DeleteMesh": { + "methods": [ + "delete_mesh" + ] + }, + "DeleteServiceBinding": { + "methods": [ + "delete_service_binding" + ] + }, + "DeleteTcpRoute": { + "methods": [ + "delete_tcp_route" + ] + }, + "DeleteTlsRoute": { + "methods": [ + "delete_tls_route" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "GetGateway": { + "methods": [ + "get_gateway" + ] + }, + "GetGrpcRoute": { + "methods": [ + "get_grpc_route" + ] + }, + "GetHttpRoute": { + "methods": [ + "get_http_route" + ] + }, + "GetMesh": { + "methods": [ + "get_mesh" + ] + }, + "GetServiceBinding": { + "methods": [ + "get_service_binding" + ] + }, + "GetTcpRoute": { + "methods": [ + "get_tcp_route" + ] + }, + "GetTlsRoute": { + "methods": [ + "get_tls_route" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "ListGateways": { + "methods": [ + "list_gateways" + ] + }, + "ListGrpcRoutes": { + "methods": [ + "list_grpc_routes" + ] + }, + "ListHttpRoutes": { + "methods": [ + "list_http_routes" + ] + }, + "ListMeshes": { + "methods": [ + "list_meshes" + ] + }, + "ListServiceBindings": { + "methods": [ + "list_service_bindings" + ] + }, + "ListTcpRoutes": { + "methods": [ + "list_tcp_routes" + ] + }, + "ListTlsRoutes": { + "methods": [ + "list_tls_routes" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + }, + "UpdateGateway": { + "methods": [ + "update_gateway" + ] + }, + "UpdateGrpcRoute": { + "methods": [ + "update_grpc_route" + ] + }, + "UpdateHttpRoute": { + "methods": [ + "update_http_route" + ] + }, + "UpdateMesh": { + "methods": [ + "update_mesh" + ] + }, + "UpdateTcpRoute": { + "methods": [ + "update_tcp_route" + ] + }, + "UpdateTlsRoute": { + "methods": [ + "update_tls_route" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/google/cloud/network_services_v1/py.typed b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed new file mode 100644 index 000000000000..dfe9bf70b7d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-services package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py new file mode 100644 index 000000000000..ffaa7e02b9ae --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DepServiceClient +from .async_client import DepServiceAsyncClient + +__all__ = ( + 'DepServiceClient', + 'DepServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py new file mode 100644 index 000000000000..cf51a467d5fe --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py @@ -0,0 +1,2148 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_services_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 + + +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_services_v1.services.dep_service import pagers +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import dep +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DepServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport +from .client import DepServiceClient + + +class DepServiceAsyncClient: + """Service describing handlers for resources.""" + + _client: DepServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DepServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DepServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DepServiceClient._DEFAULT_UNIVERSE + + lb_route_extension_path = staticmethod(DepServiceClient.lb_route_extension_path) + parse_lb_route_extension_path = staticmethod(DepServiceClient.parse_lb_route_extension_path) + lb_traffic_extension_path = staticmethod(DepServiceClient.lb_traffic_extension_path) + parse_lb_traffic_extension_path = staticmethod(DepServiceClient.parse_lb_traffic_extension_path) + common_billing_account_path = staticmethod(DepServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DepServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DepServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DepServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DepServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DepServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DepServiceClient.common_project_path) + parse_common_project_path = staticmethod(DepServiceClient.parse_common_project_path) + common_location_path = staticmethod(DepServiceClient.common_location_path) + parse_common_location_path = staticmethod(DepServiceClient.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: + DepServiceAsyncClient: The constructed client. + """ + return DepServiceClient.from_service_account_info.__func__(DepServiceAsyncClient, 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: + DepServiceAsyncClient: The constructed client. + """ + return DepServiceClient.from_service_account_file.__func__(DepServiceAsyncClient, 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 DepServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DepServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DepServiceTransport: 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 = functools.partial(type(DepServiceClient).get_transport_class, type(DepServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DepServiceTransport, Callable[..., DepServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dep 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,DepServiceTransport,Callable[..., DepServiceTransport]]]): + 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 DepServiceTransport 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 = DepServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_lb_traffic_extensions(self, + request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListLbTrafficExtensionsAsyncPager: + r"""Lists ``LbTrafficExtension`` resources 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_services_v1 + + async def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest, dict]]): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + parent (:class:`str`): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified + in the following 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager: + Message for response to listing LbTrafficExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.ListLbTrafficExtensionsRequest): + request = dep.ListLbTrafficExtensionsRequest(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_lb_traffic_extensions] + + # 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.ListLbTrafficExtensionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_lb_traffic_extension(self, + request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dep.LbTrafficExtension: + r"""Gets details of the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest, dict]]): + The request object. Message for getting a ``LbTrafficExtension`` resource. + name (:class:`str`): + Required. A name of the ``LbTrafficExtension`` resource + to get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.LbTrafficExtension: + LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.GetLbTrafficExtensionRequest): + request = dep.GetLbTrafficExtensionRequest(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_lb_traffic_extension] + + # Certain 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_lb_traffic_extension(self, + request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + lb_traffic_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ``LbTrafficExtension`` resource 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_services_v1 + + async def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest, dict]]): + The request object. Message for creating a ``LbTrafficExtension`` resource. + parent (:class:`str`): + Required. The parent resource of the + ``LbTrafficExtension`` resource. 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. + lb_traffic_extension (:class:`google.cloud.network_services_v1.types.LbTrafficExtension`): + Required. ``LbTrafficExtension`` resource to be created. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension_id (:class:`str`): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + + This corresponds to the ``lb_traffic_extension_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lb_traffic_extension, lb_traffic_extension_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.CreateLbTrafficExtensionRequest): + request = dep.CreateLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if lb_traffic_extension_id is not None: + request.lb_traffic_extension_id = lb_traffic_extension_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_lb_traffic_extension] + + # 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, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_lb_traffic_extension(self, + request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, + *, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest, dict]]): + The request object. Message for updating a ``LbTrafficExtension`` resource. + lb_traffic_extension (:class:`google.cloud.network_services_v1.types.LbTrafficExtension`): + Required. ``LbTrafficExtension`` resource being updated. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Used to specify the fields to be overwritten + in the ``LbTrafficExtension`` resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field is + overwritten if it is in the mask. If the user does not + specify a mask, then all fields are 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([lb_traffic_extension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.UpdateLbTrafficExtensionRequest): + request = dep.UpdateLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + 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_lb_traffic_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("lb_traffic_extension.name", request.lb_traffic_extension.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, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_lb_traffic_extension(self, + request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest, dict]]): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + name (:class:`str`): + Required. The name of the ``LbTrafficExtension`` + resource to delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.DeleteLbTrafficExtensionRequest): + request = dep.DeleteLbTrafficExtensionRequest(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_lb_traffic_extension] + + # Certain 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_lb_route_extensions(self, + request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListLbRouteExtensionsAsyncPager: + r"""Lists ``LbRouteExtension`` resources 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_services_v1 + + async def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest, dict]]): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + parent (:class:`str`): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in + the following 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager: + Message for response to listing LbRouteExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.ListLbRouteExtensionsRequest): + request = dep.ListLbRouteExtensionsRequest(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_lb_route_extensions] + + # 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.ListLbRouteExtensionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_lb_route_extension(self, + request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dep.LbRouteExtension: + r"""Gets details of the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetLbRouteExtensionRequest, dict]]): + The request object. Message for getting a ``LbRouteExtension`` resource. + name (:class:`str`): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.LbRouteExtension: + LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.GetLbRouteExtensionRequest): + request = dep.GetLbRouteExtensionRequest(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_lb_route_extension] + + # Certain 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_lb_route_extension(self, + request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + lb_route_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ``LbRouteExtension`` resource 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_services_v1 + + async def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest, dict]]): + The request object. Message for creating a ``LbRouteExtension`` resource. + parent (:class:`str`): + Required. The parent resource of the + ``LbRouteExtension`` resource. 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. + lb_route_extension (:class:`google.cloud.network_services_v1.types.LbRouteExtension`): + Required. ``LbRouteExtension`` resource to be created. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension_id (:class:`str`): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + + This corresponds to the ``lb_route_extension_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lb_route_extension, lb_route_extension_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.CreateLbRouteExtensionRequest): + request = dep.CreateLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if lb_route_extension_id is not None: + request.lb_route_extension_id = lb_route_extension_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_lb_route_extension] + + # 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, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_lb_route_extension(self, + request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, + *, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of the specified ``LbRouteExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest, dict]]): + The request object. Message for updating a ``LbRouteExtension`` resource. + lb_route_extension (:class:`google.cloud.network_services_v1.types.LbRouteExtension`): + Required. ``LbRouteExtension`` resource being updated. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Used to specify the fields to be overwritten + in the ``LbRouteExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten + if it is in the mask. If the user does not specify a + mask, then all fields are 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([lb_route_extension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.UpdateLbRouteExtensionRequest): + request = dep.UpdateLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + 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_lb_route_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("lb_route_extension.name", request.lb_route_extension.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, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_lb_route_extension(self, + request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest, dict]]): + The request object. Message for deleting a ``LbRouteExtension`` resource. + name (:class:`str`): + Required. The name of the ``LbRouteExtension`` resource + to delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, dep.DeleteLbRouteExtensionRequest): + request = dep.DeleteLbRouteExtensionRequest(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_lb_route_extension] + + # Certain 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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) -> "DepServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DepServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py new file mode 100644 index 000000000000..ac3e0906abda --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py @@ -0,0 +1,2498 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_services_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, 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_services_v1.services.dep_service import pagers +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import dep +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DepServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DepServiceGrpcTransport +from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport +from .transports.rest import DepServiceRestTransport + + +class DepServiceClientMeta(type): + """Metaclass for the DepService 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[DepServiceTransport]] + _transport_registry["grpc"] = DepServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DepServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DepServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DepServiceTransport]: + """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 DepServiceClient(metaclass=DepServiceClientMeta): + """Service describing handlers for resources.""" + + @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 = "networkservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{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: + DepServiceClient: 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: + DepServiceClient: 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) -> DepServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DepServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lb_route_extension_path(project: str,location: str,lb_route_extension: str,) -> str: + """Returns a fully-qualified lb_route_extension string.""" + return "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format(project=project, location=location, lb_route_extension=lb_route_extension, ) + + @staticmethod + def parse_lb_route_extension_path(path: str) -> Dict[str,str]: + """Parses a lb_route_extension path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lbRouteExtensions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def lb_traffic_extension_path(project: str,location: str,lb_traffic_extension: str,) -> str: + """Returns a fully-qualified lb_traffic_extension string.""" + return "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format(project=project, location=location, lb_traffic_extension=lb_traffic_extension, ) + + @staticmethod + def parse_lb_traffic_extension_path(path: str) -> Dict[str,str]: + """Parses a lb_traffic_extension path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lbTrafficExtensions/(?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 = DepServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = DepServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = DepServiceClient._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 = DepServiceClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = DepServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + DepServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @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, DepServiceTransport, Callable[..., DepServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dep 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,DepServiceTransport,Callable[..., DepServiceTransport]]]): + 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 DepServiceTransport 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 = DepServiceClient._read_environment_variables() + self._client_cert_source = DepServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = DepServiceClient._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 + + 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, DepServiceTransport) + if transport_provided: + # transport is a DepServiceTransport 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(DepServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + DepServiceClient._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[DepServiceTransport], Callable[..., DepServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DepServiceTransport], 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, + ) + + def list_lb_traffic_extensions(self, + request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListLbTrafficExtensionsPager: + r"""Lists ``LbTrafficExtension`` resources 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_services_v1 + + def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest, dict]): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + parent (str): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified + in the following 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsPager: + Message for response to listing LbTrafficExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.ListLbTrafficExtensionsRequest): + request = dep.ListLbTrafficExtensionsRequest(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_lb_traffic_extensions] + + # 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.ListLbTrafficExtensionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_lb_traffic_extension(self, + request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dep.LbTrafficExtension: + r"""Gets details of the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest, dict]): + The request object. Message for getting a ``LbTrafficExtension`` resource. + name (str): + Required. A name of the ``LbTrafficExtension`` resource + to get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.LbTrafficExtension: + LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.GetLbTrafficExtensionRequest): + request = dep.GetLbTrafficExtensionRequest(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_lb_traffic_extension] + + # Certain 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_lb_traffic_extension(self, + request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + lb_traffic_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new ``LbTrafficExtension`` resource 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_services_v1 + + def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest, dict]): + The request object. Message for creating a ``LbTrafficExtension`` resource. + parent (str): + Required. The parent resource of the + ``LbTrafficExtension`` resource. 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. + lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource to be created. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension_id (str): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + + This corresponds to the ``lb_traffic_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lb_traffic_extension, lb_traffic_extension_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.CreateLbTrafficExtensionRequest): + request = dep.CreateLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if lb_traffic_extension_id is not None: + request.lb_traffic_extension_id = lb_traffic_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_lb_traffic_extension] + + # 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, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_lb_traffic_extension(self, + request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, + *, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest, dict]): + The request object. Message for updating a ``LbTrafficExtension`` resource. + lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource being updated. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Used to specify the fields to be overwritten + in the ``LbTrafficExtension`` resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field is + overwritten if it is in the mask. If the user does not + specify a mask, then all fields are 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([lb_traffic_extension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.UpdateLbTrafficExtensionRequest): + request = dep.UpdateLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + 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_lb_traffic_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("lb_traffic_extension.name", request.lb_traffic_extension.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, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_lb_traffic_extension(self, + request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest, dict]): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + name (str): + Required. The name of the ``LbTrafficExtension`` + resource to delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.DeleteLbTrafficExtensionRequest): + request = dep.DeleteLbTrafficExtensionRequest(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_lb_traffic_extension] + + # Certain 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_lb_route_extensions(self, + request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListLbRouteExtensionsPager: + r"""Lists ``LbRouteExtension`` resources 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_services_v1 + + def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest, dict]): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + parent (str): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in + the following 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsPager: + Message for response to listing LbRouteExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.ListLbRouteExtensionsRequest): + request = dep.ListLbRouteExtensionsRequest(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_lb_route_extensions] + + # 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.ListLbRouteExtensionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_lb_route_extension(self, + request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dep.LbRouteExtension: + r"""Gets details of the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetLbRouteExtensionRequest, dict]): + The request object. Message for getting a ``LbRouteExtension`` resource. + name (str): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.LbRouteExtension: + LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.GetLbRouteExtensionRequest): + request = dep.GetLbRouteExtensionRequest(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_lb_route_extension] + + # Certain 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_lb_route_extension(self, + request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + lb_route_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new ``LbRouteExtension`` resource 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_services_v1 + + def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest, dict]): + The request object. Message for creating a ``LbRouteExtension`` resource. + parent (str): + Required. The parent resource of the + ``LbRouteExtension`` resource. 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. + lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource to be created. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension_id (str): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + + This corresponds to the ``lb_route_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, lb_route_extension, lb_route_extension_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.CreateLbRouteExtensionRequest): + request = dep.CreateLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if lb_route_extension_id is not None: + request.lb_route_extension_id = lb_route_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_lb_route_extension] + + # 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, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_lb_route_extension(self, + request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, + *, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of the specified ``LbRouteExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest, dict]): + The request object. Message for updating a ``LbRouteExtension`` resource. + lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource being updated. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Used to specify the fields to be overwritten + in the ``LbRouteExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten + if it is in the mask. If the user does not specify a + mask, then all fields are 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([lb_route_extension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.UpdateLbRouteExtensionRequest): + request = dep.UpdateLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + 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_lb_route_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("lb_route_extension.name", request.lb_route_extension.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, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_lb_route_extension(self, + request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest, dict]): + The request object. Message for deleting a ``LbRouteExtension`` resource. + name (str): + Required. The name of the ``LbRouteExtension`` resource + to delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, dep.DeleteLbRouteExtensionRequest): + request = dep.DeleteLbRouteExtensionRequest(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_lb_route_extension] + + # Certain 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) -> "DepServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DepServiceClient", +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py new file mode 100644 index 000000000000..97c7ce22fc34 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.network_services_v1.types import dep + + +class ListLbTrafficExtensionsPager: + """A pager for iterating through ``list_lb_traffic_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lb_traffic_extensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLbTrafficExtensions`` requests and continue to iterate + through the ``lb_traffic_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` + 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[..., dep.ListLbTrafficExtensionsResponse], + request: dep.ListLbTrafficExtensionsRequest, + response: dep.ListLbTrafficExtensionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dep.ListLbTrafficExtensionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[dep.ListLbTrafficExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[dep.LbTrafficExtension]: + for page in self.pages: + yield from page.lb_traffic_extensions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLbTrafficExtensionsAsyncPager: + """A pager for iterating through ``list_lb_traffic_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lb_traffic_extensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLbTrafficExtensions`` requests and continue to iterate + through the ``lb_traffic_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` + 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[dep.ListLbTrafficExtensionsResponse]], + request: dep.ListLbTrafficExtensionsRequest, + response: dep.ListLbTrafficExtensionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dep.ListLbTrafficExtensionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[dep.ListLbTrafficExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[dep.LbTrafficExtension]: + async def async_generator(): + async for page in self.pages: + for response in page.lb_traffic_extensions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLbRouteExtensionsPager: + """A pager for iterating through ``list_lb_route_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lb_route_extensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLbRouteExtensions`` requests and continue to iterate + through the ``lb_route_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` + 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[..., dep.ListLbRouteExtensionsResponse], + request: dep.ListLbRouteExtensionsRequest, + response: dep.ListLbRouteExtensionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dep.ListLbRouteExtensionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[dep.ListLbRouteExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[dep.LbRouteExtension]: + for page in self.pages: + yield from page.lb_route_extensions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLbRouteExtensionsAsyncPager: + """A pager for iterating through ``list_lb_route_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lb_route_extensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLbRouteExtensions`` requests and continue to iterate + through the ``lb_route_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` + 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[dep.ListLbRouteExtensionsResponse]], + request: dep.ListLbRouteExtensionsRequest, + response: dep.ListLbRouteExtensionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dep.ListLbRouteExtensionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[dep.ListLbRouteExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[dep.LbRouteExtension]: + async def async_generator(): + async for page in self.pages: + for response in page.lb_route_extensions: + 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-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py new file mode 100644 index 000000000000..e4e3e262c9ee --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DepServiceTransport +from .grpc import DepServiceGrpcTransport +from .grpc_asyncio import DepServiceGrpcAsyncIOTransport +from .rest import DepServiceRestTransport +from .rest import DepServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DepServiceTransport]] +_transport_registry['grpc'] = DepServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DepServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DepServiceRestTransport + +__all__ = ( + 'DepServiceTransport', + 'DepServiceGrpcTransport', + 'DepServiceGrpcAsyncIOTransport', + 'DepServiceRestTransport', + 'DepServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py new file mode 100644 index 000000000000..ed22020e6315 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_services_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import dep +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__) + + +class DepServiceTransport(abc.ABC): + """Abstract transport class for DepService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networkservices.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: 'networkservices.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 no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_lb_traffic_extensions: gapic_v1.method.wrap_method( + self.list_lb_traffic_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_traffic_extension: gapic_v1.method.wrap_method( + self.get_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_traffic_extension: gapic_v1.method.wrap_method( + self.create_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_traffic_extension: gapic_v1.method.wrap_method( + self.update_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_traffic_extension: gapic_v1.method.wrap_method( + self.delete_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_lb_route_extensions: gapic_v1.method.wrap_method( + self.list_lb_route_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_route_extension: gapic_v1.method.wrap_method( + self.get_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_route_extension: gapic_v1.method.wrap_method( + self.create_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_route_extension: gapic_v1.method.wrap_method( + self.update_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_route_extension: gapic_v1.method.wrap_method( + self.delete_lb_route_extension, + 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_lb_traffic_extensions(self) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + Union[ + dep.ListLbTrafficExtensionsResponse, + Awaitable[dep.ListLbTrafficExtensionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_lb_traffic_extension(self) -> Callable[ + [dep.GetLbTrafficExtensionRequest], + Union[ + dep.LbTrafficExtension, + Awaitable[dep.LbTrafficExtension] + ]]: + raise NotImplementedError() + + @property + def create_lb_traffic_extension(self) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_lb_traffic_extension(self) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_lb_traffic_extension(self) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_lb_route_extensions(self) -> Callable[ + [dep.ListLbRouteExtensionsRequest], + Union[ + dep.ListLbRouteExtensionsResponse, + Awaitable[dep.ListLbRouteExtensionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_lb_route_extension(self) -> Callable[ + [dep.GetLbRouteExtensionRequest], + Union[ + dep.LbRouteExtension, + Awaitable[dep.LbRouteExtension] + ]]: + raise NotImplementedError() + + @property + def create_lb_route_extension(self) -> Callable[ + [dep.CreateLbRouteExtensionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_lb_route_extension(self) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_lb_route_extension(self) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], + 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__ = ( + 'DepServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py new file mode 100644 index 000000000000..589c48b2a03f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py @@ -0,0 +1,718 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import dep +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 DepServiceTransport, DEFAULT_CLIENT_INFO + + +class DepServiceGrpcTransport(DepServiceTransport): + """gRPC backend transport for DepService. + + Service describing handlers for resources. + + 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 = 'networkservices.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: 'networkservices.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 = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networkservices.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_lb_traffic_extensions(self) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + dep.ListLbTrafficExtensionsResponse]: + r"""Return a callable for the list lb traffic extensions method over gRPC. + + Lists ``LbTrafficExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbTrafficExtensionsRequest], + ~.ListLbTrafficExtensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_traffic_extensions' not in self._stubs: + self._stubs['list_lb_traffic_extensions'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/ListLbTrafficExtensions', + request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, + response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, + ) + return self._stubs['list_lb_traffic_extensions'] + + @property + def get_lb_traffic_extension(self) -> Callable[ + [dep.GetLbTrafficExtensionRequest], + dep.LbTrafficExtension]: + r"""Return a callable for the get lb traffic extension method over gRPC. + + Gets details of the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.GetLbTrafficExtensionRequest], + ~.LbTrafficExtension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_traffic_extension' not in self._stubs: + self._stubs['get_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/GetLbTrafficExtension', + request_serializer=dep.GetLbTrafficExtensionRequest.serialize, + response_deserializer=dep.LbTrafficExtension.deserialize, + ) + return self._stubs['get_lb_traffic_extension'] + + @property + def create_lb_traffic_extension(self) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create lb traffic extension method over gRPC. + + Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbTrafficExtensionRequest], + ~.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_lb_traffic_extension' not in self._stubs: + self._stubs['create_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/CreateLbTrafficExtension', + request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_lb_traffic_extension'] + + @property + def update_lb_traffic_extension(self) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update lb traffic extension method over gRPC. + + Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + Returns: + Callable[[~.UpdateLbTrafficExtensionRequest], + ~.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_lb_traffic_extension' not in self._stubs: + self._stubs['update_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/UpdateLbTrafficExtension', + request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_lb_traffic_extension'] + + @property + def delete_lb_traffic_extension(self) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete lb traffic extension method over gRPC. + + Deletes the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.DeleteLbTrafficExtensionRequest], + ~.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_lb_traffic_extension' not in self._stubs: + self._stubs['delete_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/DeleteLbTrafficExtension', + request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_lb_traffic_extension'] + + @property + def list_lb_route_extensions(self) -> Callable[ + [dep.ListLbRouteExtensionsRequest], + dep.ListLbRouteExtensionsResponse]: + r"""Return a callable for the list lb route extensions method over gRPC. + + Lists ``LbRouteExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbRouteExtensionsRequest], + ~.ListLbRouteExtensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_route_extensions' not in self._stubs: + self._stubs['list_lb_route_extensions'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/ListLbRouteExtensions', + request_serializer=dep.ListLbRouteExtensionsRequest.serialize, + response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, + ) + return self._stubs['list_lb_route_extensions'] + + @property + def get_lb_route_extension(self) -> Callable[ + [dep.GetLbRouteExtensionRequest], + dep.LbRouteExtension]: + r"""Return a callable for the get lb route extension method over gRPC. + + Gets details of the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.GetLbRouteExtensionRequest], + ~.LbRouteExtension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_route_extension' not in self._stubs: + self._stubs['get_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/GetLbRouteExtension', + request_serializer=dep.GetLbRouteExtensionRequest.serialize, + response_deserializer=dep.LbRouteExtension.deserialize, + ) + return self._stubs['get_lb_route_extension'] + + @property + def create_lb_route_extension(self) -> Callable[ + [dep.CreateLbRouteExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create lb route extension method over gRPC. + + Creates a new ``LbRouteExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbRouteExtensionRequest], + ~.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_lb_route_extension' not in self._stubs: + self._stubs['create_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/CreateLbRouteExtension', + request_serializer=dep.CreateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_lb_route_extension'] + + @property + def update_lb_route_extension(self) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update lb route extension method over gRPC. + + Updates the parameters of the specified ``LbRouteExtension`` + resource. + + Returns: + Callable[[~.UpdateLbRouteExtensionRequest], + ~.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_lb_route_extension' not in self._stubs: + self._stubs['update_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/UpdateLbRouteExtension', + request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_lb_route_extension'] + + @property + def delete_lb_route_extension(self) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete lb route extension method over gRPC. + + Deletes the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.DeleteLbRouteExtensionRequest], + ~.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_lb_route_extension' not in self._stubs: + self._stubs['delete_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/DeleteLbRouteExtension', + request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_lb_route_extension'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DepServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..cdd21e8e0f62 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py @@ -0,0 +1,773 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import dep +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 DepServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DepServiceGrpcTransport + + +class DepServiceGrpcAsyncIOTransport(DepServiceTransport): + """gRPC AsyncIO backend transport for DepService. + + Service describing handlers for resources. + + 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 = 'networkservices.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 = 'networkservices.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: 'networkservices.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 = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_lb_traffic_extensions(self) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + Awaitable[dep.ListLbTrafficExtensionsResponse]]: + r"""Return a callable for the list lb traffic extensions method over gRPC. + + Lists ``LbTrafficExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbTrafficExtensionsRequest], + Awaitable[~.ListLbTrafficExtensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_traffic_extensions' not in self._stubs: + self._stubs['list_lb_traffic_extensions'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/ListLbTrafficExtensions', + request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, + response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, + ) + return self._stubs['list_lb_traffic_extensions'] + + @property + def get_lb_traffic_extension(self) -> Callable[ + [dep.GetLbTrafficExtensionRequest], + Awaitable[dep.LbTrafficExtension]]: + r"""Return a callable for the get lb traffic extension method over gRPC. + + Gets details of the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.GetLbTrafficExtensionRequest], + Awaitable[~.LbTrafficExtension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_traffic_extension' not in self._stubs: + self._stubs['get_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/GetLbTrafficExtension', + request_serializer=dep.GetLbTrafficExtensionRequest.serialize, + response_deserializer=dep.LbTrafficExtension.deserialize, + ) + return self._stubs['get_lb_traffic_extension'] + + @property + def create_lb_traffic_extension(self) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create lb traffic extension method over gRPC. + + Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbTrafficExtensionRequest], + 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_lb_traffic_extension' not in self._stubs: + self._stubs['create_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/CreateLbTrafficExtension', + request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_lb_traffic_extension'] + + @property + def update_lb_traffic_extension(self) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update lb traffic extension method over gRPC. + + Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + Returns: + Callable[[~.UpdateLbTrafficExtensionRequest], + 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_lb_traffic_extension' not in self._stubs: + self._stubs['update_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/UpdateLbTrafficExtension', + request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_lb_traffic_extension'] + + @property + def delete_lb_traffic_extension(self) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete lb traffic extension method over gRPC. + + Deletes the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.DeleteLbTrafficExtensionRequest], + 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_lb_traffic_extension' not in self._stubs: + self._stubs['delete_lb_traffic_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/DeleteLbTrafficExtension', + request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_lb_traffic_extension'] + + @property + def list_lb_route_extensions(self) -> Callable[ + [dep.ListLbRouteExtensionsRequest], + Awaitable[dep.ListLbRouteExtensionsResponse]]: + r"""Return a callable for the list lb route extensions method over gRPC. + + Lists ``LbRouteExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbRouteExtensionsRequest], + Awaitable[~.ListLbRouteExtensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_route_extensions' not in self._stubs: + self._stubs['list_lb_route_extensions'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/ListLbRouteExtensions', + request_serializer=dep.ListLbRouteExtensionsRequest.serialize, + response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, + ) + return self._stubs['list_lb_route_extensions'] + + @property + def get_lb_route_extension(self) -> Callable[ + [dep.GetLbRouteExtensionRequest], + Awaitable[dep.LbRouteExtension]]: + r"""Return a callable for the get lb route extension method over gRPC. + + Gets details of the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.GetLbRouteExtensionRequest], + Awaitable[~.LbRouteExtension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_lb_route_extension' not in self._stubs: + self._stubs['get_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/GetLbRouteExtension', + request_serializer=dep.GetLbRouteExtensionRequest.serialize, + response_deserializer=dep.LbRouteExtension.deserialize, + ) + return self._stubs['get_lb_route_extension'] + + @property + def create_lb_route_extension(self) -> Callable[ + [dep.CreateLbRouteExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create lb route extension method over gRPC. + + Creates a new ``LbRouteExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbRouteExtensionRequest], + 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_lb_route_extension' not in self._stubs: + self._stubs['create_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/CreateLbRouteExtension', + request_serializer=dep.CreateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_lb_route_extension'] + + @property + def update_lb_route_extension(self) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update lb route extension method over gRPC. + + Updates the parameters of the specified ``LbRouteExtension`` + resource. + + Returns: + Callable[[~.UpdateLbRouteExtensionRequest], + 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_lb_route_extension' not in self._stubs: + self._stubs['update_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/UpdateLbRouteExtension', + request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_lb_route_extension'] + + @property + def delete_lb_route_extension(self) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete lb route extension method over gRPC. + + Deletes the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.DeleteLbRouteExtensionRequest], + 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_lb_route_extension' not in self._stubs: + self._stubs['delete_lb_route_extension'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.DepService/DeleteLbRouteExtension', + request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_lb_route_extension'] + + 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_lb_traffic_extensions: gapic_v1.method_async.wrap_method( + self.list_lb_traffic_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_traffic_extension: gapic_v1.method_async.wrap_method( + self.get_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_traffic_extension: gapic_v1.method_async.wrap_method( + self.create_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_traffic_extension: gapic_v1.method_async.wrap_method( + self.update_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_traffic_extension: gapic_v1.method_async.wrap_method( + self.delete_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_lb_route_extensions: gapic_v1.method_async.wrap_method( + self.list_lb_route_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_route_extension: gapic_v1.method_async.wrap_method( + self.get_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_route_extension: gapic_v1.method_async.wrap_method( + self.create_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_route_extension: gapic_v1.method_async.wrap_method( + self.update_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_route_extension: gapic_v1.method_async.wrap_method( + self.delete_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DepServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py new file mode 100644 index 000000000000..e1cc3a736fec --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py @@ -0,0 +1,2226 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.network_services_v1.types import dep +from google.longrunning import operations_pb2 # type: ignore + +from .base import DepServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DepServiceRestInterceptor: + """Interceptor for DepService. + + 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 DepServiceRestTransport. + + .. code-block:: python + class MyCustomDepServiceInterceptor(DepServiceRestInterceptor): + def pre_create_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_lb_route_extensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_lb_route_extensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_lb_traffic_extensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_lb_traffic_extensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DepServiceRestTransport(interceptor=MyCustomDepServiceInterceptor()) + client = DepServiceClient(transport=transport) + + + """ + def pre_create_lb_route_extension(self, request: dep.CreateLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.CreateLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_create_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_lb_route_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_create_lb_traffic_extension(self, request: dep.CreateLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.CreateLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_create_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_lb_traffic_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_delete_lb_route_extension(self, request: dep.DeleteLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.DeleteLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_lb_route_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_delete_lb_traffic_extension(self, request: dep.DeleteLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.DeleteLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_lb_traffic_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_get_lb_route_extension(self, request: dep.GetLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.GetLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_lb_route_extension(self, response: dep.LbRouteExtension) -> dep.LbRouteExtension: + """Post-rpc interceptor for get_lb_route_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_get_lb_traffic_extension(self, request: dep.GetLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.GetLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_lb_traffic_extension(self, response: dep.LbTrafficExtension) -> dep.LbTrafficExtension: + """Post-rpc interceptor for get_lb_traffic_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_list_lb_route_extensions(self, request: dep.ListLbRouteExtensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.ListLbRouteExtensionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_lb_route_extensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_lb_route_extensions(self, response: dep.ListLbRouteExtensionsResponse) -> dep.ListLbRouteExtensionsResponse: + """Post-rpc interceptor for list_lb_route_extensions + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_list_lb_traffic_extensions(self, request: dep.ListLbTrafficExtensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.ListLbTrafficExtensionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_lb_traffic_extensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_lb_traffic_extensions(self, response: dep.ListLbTrafficExtensionsResponse) -> dep.ListLbTrafficExtensionsResponse: + """Post-rpc interceptor for list_lb_traffic_extensions + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_update_lb_route_extension(self, request: dep.UpdateLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.UpdateLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_update_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_lb_route_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + def pre_update_lb_traffic_extension(self, request: dep.UpdateLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.UpdateLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_update_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_lb_traffic_extension + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService 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 DepService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DepServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DepServiceRestInterceptor + + +class DepServiceRestTransport(DepServiceTransport): + """REST backend transport for DepService. + + Service describing handlers for resources. + + 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 = 'networkservices.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[DepServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DepServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateLbRouteExtension(DepServiceRestStub): + def __hash__(self): + return hash("CreateLbRouteExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "lbRouteExtensionId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.CreateLbRouteExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create lb route extension method over HTTP. + + Args: + request (~.dep.CreateLbRouteExtensionRequest): + The request object. Message for creating a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/lbRouteExtensions', + 'body': 'lb_route_extension', + }, + ] + request, metadata = self._interceptor.pre_create_lb_route_extension(request, metadata) + pb_request = dep.CreateLbRouteExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_lb_route_extension(resp) + return resp + + class _CreateLbTrafficExtension(DepServiceRestStub): + def __hash__(self): + return hash("CreateLbTrafficExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "lbTrafficExtensionId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.CreateLbTrafficExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create lb traffic + extension method over HTTP. + + Args: + request (~.dep.CreateLbTrafficExtensionRequest): + The request object. Message for creating a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/lbTrafficExtensions', + 'body': 'lb_traffic_extension', + }, + ] + request, metadata = self._interceptor.pre_create_lb_traffic_extension(request, metadata) + pb_request = dep.CreateLbTrafficExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_lb_traffic_extension(resp) + return resp + + class _DeleteLbRouteExtension(DepServiceRestStub): + def __hash__(self): + return hash("DeleteLbRouteExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.DeleteLbRouteExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete lb route extension method over HTTP. + + Args: + request (~.dep.DeleteLbRouteExtensionRequest): + The request object. Message for deleting a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/lbRouteExtensions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_lb_route_extension(request, metadata) + pb_request = dep.DeleteLbRouteExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_lb_route_extension(resp) + return resp + + class _DeleteLbTrafficExtension(DepServiceRestStub): + def __hash__(self): + return hash("DeleteLbTrafficExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.DeleteLbTrafficExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete lb traffic + extension method over HTTP. + + Args: + request (~.dep.DeleteLbTrafficExtensionRequest): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/lbTrafficExtensions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_lb_traffic_extension(request, metadata) + pb_request = dep.DeleteLbTrafficExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_lb_traffic_extension(resp) + return resp + + class _GetLbRouteExtension(DepServiceRestStub): + def __hash__(self): + return hash("GetLbRouteExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.GetLbRouteExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> dep.LbRouteExtension: + r"""Call the get lb route extension method over HTTP. + + Args: + request (~.dep.GetLbRouteExtensionRequest): + The request object. Message for getting a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dep.LbRouteExtension: + ``LbRouteExtension`` is a resource that lets you control + where traffic is routed to for a given request. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/lbRouteExtensions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_lb_route_extension(request, metadata) + pb_request = dep.GetLbRouteExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.LbRouteExtension() + pb_resp = dep.LbRouteExtension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_lb_route_extension(resp) + return resp + + class _GetLbTrafficExtension(DepServiceRestStub): + def __hash__(self): + return hash("GetLbTrafficExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.GetLbTrafficExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> dep.LbTrafficExtension: + r"""Call the get lb traffic extension method over HTTP. + + Args: + request (~.dep.GetLbTrafficExtensionRequest): + The request object. Message for getting a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dep.LbTrafficExtension: + ``LbTrafficExtension`` is a resource that lets the + extension service modify the headers and payloads of + both requests and responses without impacting the choice + of backend services or any other security policies + associated with the backend service. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/lbTrafficExtensions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_lb_traffic_extension(request, metadata) + pb_request = dep.GetLbTrafficExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.LbTrafficExtension() + pb_resp = dep.LbTrafficExtension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_lb_traffic_extension(resp) + return resp + + class _ListLbRouteExtensions(DepServiceRestStub): + def __hash__(self): + return hash("ListLbRouteExtensions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.ListLbRouteExtensionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> dep.ListLbRouteExtensionsResponse: + r"""Call the list lb route extensions method over HTTP. + + Args: + request (~.dep.ListLbRouteExtensionsRequest): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dep.ListLbRouteExtensionsResponse: + Message for response to listing ``LbRouteExtension`` + resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/lbRouteExtensions', + }, + ] + request, metadata = self._interceptor.pre_list_lb_route_extensions(request, metadata) + pb_request = dep.ListLbRouteExtensionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ListLbRouteExtensionsResponse() + pb_resp = dep.ListLbRouteExtensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_lb_route_extensions(resp) + return resp + + class _ListLbTrafficExtensions(DepServiceRestStub): + def __hash__(self): + return hash("ListLbTrafficExtensions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.ListLbTrafficExtensionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> dep.ListLbTrafficExtensionsResponse: + r"""Call the list lb traffic + extensions method over HTTP. + + Args: + request (~.dep.ListLbTrafficExtensionsRequest): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dep.ListLbTrafficExtensionsResponse: + Message for response to listing ``LbTrafficExtension`` + resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/lbTrafficExtensions', + }, + ] + request, metadata = self._interceptor.pre_list_lb_traffic_extensions(request, metadata) + pb_request = dep.ListLbTrafficExtensionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ListLbTrafficExtensionsResponse() + pb_resp = dep.ListLbTrafficExtensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_lb_traffic_extensions(resp) + return resp + + class _UpdateLbRouteExtension(DepServiceRestStub): + def __hash__(self): + return hash("UpdateLbRouteExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.UpdateLbRouteExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update lb route extension method over HTTP. + + Args: + request (~.dep.UpdateLbRouteExtensionRequest): + The request object. Message for updating a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}', + 'body': 'lb_route_extension', + }, + ] + request, metadata = self._interceptor.pre_update_lb_route_extension(request, metadata) + pb_request = dep.UpdateLbRouteExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_lb_route_extension(resp) + return resp + + class _UpdateLbTrafficExtension(DepServiceRestStub): + def __hash__(self): + return hash("UpdateLbTrafficExtension") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: dep.UpdateLbTrafficExtensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update lb traffic + extension method over HTTP. + + Args: + request (~.dep.UpdateLbTrafficExtensionRequest): + The request object. Message for updating a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}', + 'body': 'lb_traffic_extension', + }, + ] + request, metadata = self._interceptor.pre_update_lb_traffic_extension(request, metadata) + pb_request = dep.UpdateLbTrafficExtensionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_lb_traffic_extension(resp) + return resp + + @property + def create_lb_route_extension(self) -> Callable[ + [dep.CreateLbRouteExtensionRequest], + 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._CreateLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_lb_traffic_extension(self) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], + 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._CreateLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_lb_route_extension(self) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], + 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._DeleteLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_lb_traffic_extension(self) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], + 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._DeleteLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lb_route_extension(self) -> Callable[ + [dep.GetLbRouteExtensionRequest], + dep.LbRouteExtension]: + # 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._GetLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lb_traffic_extension(self) -> Callable[ + [dep.GetLbTrafficExtensionRequest], + dep.LbTrafficExtension]: + # 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._GetLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_lb_route_extensions(self) -> Callable[ + [dep.ListLbRouteExtensionsRequest], + dep.ListLbRouteExtensionsResponse]: + # 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._ListLbRouteExtensions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_lb_traffic_extensions(self) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + dep.ListLbTrafficExtensionsResponse]: + # 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._ListLbTrafficExtensions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_lb_route_extension(self) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], + 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._UpdateLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_lb_traffic_extension(self) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], + 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._UpdateLbTrafficExtension(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(DepServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(DepServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DepServiceRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DepServiceRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DepServiceRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(DepServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DepServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DepServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DepServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DepServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py new file mode 100644 index 000000000000..1711b5d29828 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 NetworkServicesClient +from .async_client import NetworkServicesAsyncClient + +__all__ = ( + 'NetworkServicesClient', + 'NetworkServicesAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py new file mode 100644 index 000000000000..a4efe8d12e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py @@ -0,0 +1,5791 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_services_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 + + +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_services_v1.services.network_services import pagers +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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 NetworkServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .client import NetworkServicesClient + + +class NetworkServicesAsyncClient: + """""" + + _client: NetworkServicesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NetworkServicesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NetworkServicesClient._DEFAULT_UNIVERSE + + authorization_policy_path = staticmethod(NetworkServicesClient.authorization_policy_path) + parse_authorization_policy_path = staticmethod(NetworkServicesClient.parse_authorization_policy_path) + backend_service_path = staticmethod(NetworkServicesClient.backend_service_path) + parse_backend_service_path = staticmethod(NetworkServicesClient.parse_backend_service_path) + client_tls_policy_path = staticmethod(NetworkServicesClient.client_tls_policy_path) + parse_client_tls_policy_path = staticmethod(NetworkServicesClient.parse_client_tls_policy_path) + endpoint_policy_path = staticmethod(NetworkServicesClient.endpoint_policy_path) + parse_endpoint_policy_path = staticmethod(NetworkServicesClient.parse_endpoint_policy_path) + gateway_path = staticmethod(NetworkServicesClient.gateway_path) + parse_gateway_path = staticmethod(NetworkServicesClient.parse_gateway_path) + grpc_route_path = staticmethod(NetworkServicesClient.grpc_route_path) + parse_grpc_route_path = staticmethod(NetworkServicesClient.parse_grpc_route_path) + http_route_path = staticmethod(NetworkServicesClient.http_route_path) + parse_http_route_path = staticmethod(NetworkServicesClient.parse_http_route_path) + mesh_path = staticmethod(NetworkServicesClient.mesh_path) + parse_mesh_path = staticmethod(NetworkServicesClient.parse_mesh_path) + server_tls_policy_path = staticmethod(NetworkServicesClient.server_tls_policy_path) + parse_server_tls_policy_path = staticmethod(NetworkServicesClient.parse_server_tls_policy_path) + service_binding_path = staticmethod(NetworkServicesClient.service_binding_path) + parse_service_binding_path = staticmethod(NetworkServicesClient.parse_service_binding_path) + tcp_route_path = staticmethod(NetworkServicesClient.tcp_route_path) + parse_tcp_route_path = staticmethod(NetworkServicesClient.parse_tcp_route_path) + tls_route_path = staticmethod(NetworkServicesClient.tls_route_path) + parse_tls_route_path = staticmethod(NetworkServicesClient.parse_tls_route_path) + common_billing_account_path = staticmethod(NetworkServicesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(NetworkServicesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(NetworkServicesClient.common_folder_path) + parse_common_folder_path = staticmethod(NetworkServicesClient.parse_common_folder_path) + common_organization_path = staticmethod(NetworkServicesClient.common_organization_path) + parse_common_organization_path = staticmethod(NetworkServicesClient.parse_common_organization_path) + common_project_path = staticmethod(NetworkServicesClient.common_project_path) + parse_common_project_path = staticmethod(NetworkServicesClient.parse_common_project_path) + common_location_path = staticmethod(NetworkServicesClient.common_location_path) + parse_common_location_path = staticmethod(NetworkServicesClient.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: + NetworkServicesAsyncClient: The constructed client. + """ + return NetworkServicesClient.from_service_account_info.__func__(NetworkServicesAsyncClient, 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: + NetworkServicesAsyncClient: The constructed client. + """ + return NetworkServicesClient.from_service_account_file.__func__(NetworkServicesAsyncClient, 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 NetworkServicesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NetworkServicesTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkServicesTransport: 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 = functools.partial(type(NetworkServicesClient).get_transport_class, type(NetworkServicesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkServicesTransport, Callable[..., NetworkServicesTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network services 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,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): + 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 NetworkServicesTransport 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 = NetworkServicesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_endpoint_policies(self, + request: Optional[Union[endpoint_policy.ListEndpointPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointPoliciesAsyncPager: + r"""Lists EndpointPolicies 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_services_v1 + + async def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListEndpointPoliciesRequest, dict]]): + The request object. Request used with the + ListEndpointPolicies method. + parent (:class:`str`): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the + format ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesAsyncPager: + Response returned by the + ListEndpointPolicies 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, endpoint_policy.ListEndpointPoliciesRequest): + request = endpoint_policy.ListEndpointPoliciesRequest(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_endpoint_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.ListEndpointPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint_policy(self, + request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Gets details of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetEndpointPolicyRequest, dict]]): + The request object. Request used with the + GetEndpointPolicy method. + name (:class:`str`): + Required. A name of the EndpointPolicy to get. Must be + in the format + ``projects/*/locations/global/endpointPolicies/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, endpoint_policy.GetEndpointPolicyRequest): + request = endpoint_policy.GetEndpointPolicyRequest(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_endpoint_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_endpoint_policy(self, + request: Optional[Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + endpoint_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new EndpointPolicy 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_services_v1 + + async def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_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_services_v1.types.CreateEndpointPolicyRequest, dict]]): + The request object. Request used with the + CreateEndpointPolicy method. + parent (:class:`str`): + Required. The parent resource of the EndpointPolicy. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy (:class:`google.cloud.network_services_v1.types.EndpointPolicy`): + Required. EndpointPolicy resource to + be created. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy_id (:class:`str`): + Required. Short name of the + EndpointPolicy resource to be created. + E.g. "CustomECS". + + This corresponds to the ``endpoint_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, endpoint_policy, endpoint_policy_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_endpoint_policy.CreateEndpointPolicyRequest): + request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if endpoint_policy_id is not None: + request.endpoint_policy_id = endpoint_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_endpoint_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_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_endpoint_policy(self, + request: Optional[Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict]] = None, + *, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_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_services_v1.types.UpdateEndpointPolicyRequest, dict]]): + The request object. Request used with the + UpdateEndpointPolicy method. + endpoint_policy (:class:`google.cloud.network_services_v1.types.EndpointPolicy`): + Required. Updated EndpointPolicy + resource. + + This corresponds to the ``endpoint_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 EndpointPolicy 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint_policy, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_endpoint_policy.UpdateEndpointPolicyRequest): + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint_policy is not None: + request.endpoint_policy = endpoint_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_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint_policy.name", request.endpoint_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_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_endpoint_policy(self, + request: Optional[Union[endpoint_policy.DeleteEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_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_services_v1.types.DeleteEndpointPolicyRequest, dict]]): + The request object. Request used with the + DeleteEndpointPolicy method. + name (:class:`str`): + Required. A name of the EndpointPolicy to delete. Must + be in the format + ``projects/*/locations/global/endpointPolicies/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, endpoint_policy.DeleteEndpointPolicyRequest): + request = endpoint_policy.DeleteEndpointPolicyRequest(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_endpoint_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_gateways(self, + request: Optional[Union[gateway.ListGatewaysRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGatewaysAsyncPager: + r"""Lists Gateways 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_services_v1 + + async def sample_list_gateways(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListGatewaysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gateways(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListGatewaysRequest, dict]]): + The request object. Request used with the ListGateways + method. + parent (:class:`str`): + Required. The project and location from which the + Gateways should be listed, specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysAsyncPager: + Response returned by the ListGateways + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, gateway.ListGatewaysRequest): + request = gateway.ListGatewaysRequest(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_gateways] + + # 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.ListGatewaysAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_gateway(self, + request: Optional[Union[gateway.GetGatewayRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gateway.Gateway: + r"""Gets details of a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetGatewayRequest( + name="name_value", + ) + + # Make the request + response = await client.get_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetGatewayRequest, dict]]): + The request object. Request used by the GetGateway + method. + name (:class:`str`): + Required. A name of the Gateway to get. Must be in the + format ``projects/*/locations/*/gateways/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.Gateway: + Gateway represents the configuration + for a proxy, typically a load balancer. + It captures the ip:port over which the + services are exposed by the proxy, along + with any policy configurations. Routes + have reference to to Gateways to dictate + how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, gateway.GetGatewayRequest): + request = gateway.GetGatewayRequest(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_gateway] + + # Certain 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_gateway(self, + request: Optional[Union[gcn_gateway.CreateGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway: Optional[gcn_gateway.Gateway] = None, + gateway_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Gateway 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_services_v1 + + async def sample_create_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.CreateGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + gateway=gateway, + ) + + # Make the request + operation = client.create_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateGatewayRequest, dict]]): + The request object. Request used by the CreateGateway + method. + parent (:class:`str`): + Required. The parent resource of the Gateway. Must be in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway (:class:`google.cloud.network_services_v1.types.Gateway`): + Required. Gateway resource to be + created. + + This corresponds to the ``gateway`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. Short name of the Gateway + resource to be created. + + This corresponds to the ``gateway_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. + It captures the ip:port over which the services are + exposed by the proxy, along with any policy + configurations. Routes have reference to to Gateways + to dictate how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway, gateway_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_gateway.CreateGatewayRequest): + request = gcn_gateway.CreateGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway is not None: + request.gateway = gateway + if gateway_id is not None: + request.gateway_id = gateway_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_gateway] + + # 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_gateway.Gateway, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_gateway(self, + request: Optional[Union[gcn_gateway.UpdateGatewayRequest, dict]] = None, + *, + gateway: Optional[gcn_gateway.Gateway] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.UpdateGatewayRequest( + gateway=gateway, + ) + + # Make the request + operation = client.update_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateGatewayRequest, dict]]): + The request object. Request used by the UpdateGateway + method. + gateway (:class:`google.cloud.network_services_v1.types.Gateway`): + Required. Updated Gateway resource. + This corresponds to the ``gateway`` 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 Gateway 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. + It captures the ip:port over which the services are + exposed by the proxy, along with any policy + configurations. Routes have reference to to Gateways + to dictate how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([gateway, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_gateway.UpdateGatewayRequest): + request = gcn_gateway.UpdateGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if gateway is not None: + request.gateway = gateway + 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_gateway] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("gateway.name", request.gateway.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_gateway.Gateway, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_gateway(self, + request: Optional[Union[gateway.DeleteGatewayRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGatewayRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteGatewayRequest, dict]]): + The request object. Request used by the DeleteGateway + method. + name (:class:`str`): + Required. A name of the Gateway to delete. Must be in + the format ``projects/*/locations/*/gateways/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, gateway.DeleteGatewayRequest): + request = gateway.DeleteGatewayRequest(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_gateway] + + # Certain 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_grpc_routes(self, + request: Optional[Union[grpc_route.ListGrpcRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGrpcRoutesAsyncPager: + r"""Lists GrpcRoutes 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_services_v1 + + async def sample_list_grpc_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListGrpcRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_grpc_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListGrpcRoutesRequest, dict]]): + The request object. Request used with the ListGrpcRoutes + method. + parent (:class:`str`): + Required. The project and location from which the + GrpcRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesAsyncPager: + Response returned by the + ListGrpcRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, grpc_route.ListGrpcRoutesRequest): + request = grpc_route.ListGrpcRoutesRequest(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_grpc_routes] + + # 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.ListGrpcRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_grpc_route(self, + request: Optional[Union[grpc_route.GetGrpcRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grpc_route.GrpcRoute: + r"""Gets details of a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetGrpcRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_grpc_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetGrpcRouteRequest, dict]]): + The request object. Request used by the GetGrpcRoute + method. + name (:class:`str`): + Required. A name of the GrpcRoute to get. Must be in the + format ``projects/*/locations/global/grpcRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.GrpcRoute: + GrpcRoute is the resource defining + how gRPC traffic routed by a Mesh or + Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, grpc_route.GetGrpcRouteRequest): + request = grpc_route.GetGrpcRouteRequest(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_grpc_route] + + # Certain 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_grpc_route(self, + request: Optional[Union[gcn_grpc_route.CreateGrpcRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, + grpc_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new GrpcRoute 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_services_v1 + + async def sample_create_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateGrpcRouteRequest( + parent="parent_value", + grpc_route_id="grpc_route_id_value", + grpc_route=grpc_route, + ) + + # Make the request + operation = client.create_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateGrpcRouteRequest, dict]]): + The request object. Request used by the CreateGrpcRoute + method. + parent (:class:`str`): + Required. The parent resource of the GrpcRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + grpc_route (:class:`google.cloud.network_services_v1.types.GrpcRoute`): + Required. GrpcRoute resource to be + created. + + This corresponds to the ``grpc_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + grpc_route_id (:class:`str`): + Required. Short name of the GrpcRoute + resource to be created. + + This corresponds to the ``grpc_route_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh + or Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, grpc_route, grpc_route_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_grpc_route.CreateGrpcRouteRequest): + request = gcn_grpc_route.CreateGrpcRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if grpc_route is not None: + request.grpc_route = grpc_route + if grpc_route_id is not None: + request.grpc_route_id = grpc_route_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_grpc_route] + + # 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_grpc_route.GrpcRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_grpc_route(self, + request: Optional[Union[gcn_grpc_route.UpdateGrpcRouteRequest, dict]] = None, + *, + grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateGrpcRouteRequest( + grpc_route=grpc_route, + ) + + # Make the request + operation = client.update_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateGrpcRouteRequest, dict]]): + The request object. Request used by the UpdateGrpcRoute + method. + grpc_route (:class:`google.cloud.network_services_v1.types.GrpcRoute`): + Required. Updated GrpcRoute resource. + This corresponds to the ``grpc_route`` 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 GrpcRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh + or Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([grpc_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_grpc_route.UpdateGrpcRouteRequest): + request = gcn_grpc_route.UpdateGrpcRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if grpc_route is not None: + request.grpc_route = grpc_route + 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_grpc_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("grpc_route.name", request.grpc_route.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_grpc_route.GrpcRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_grpc_route(self, + request: Optional[Union[grpc_route.DeleteGrpcRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGrpcRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteGrpcRouteRequest, dict]]): + The request object. Request used by the DeleteGrpcRoute + method. + name (:class:`str`): + Required. A name of the GrpcRoute to delete. Must be in + the format ``projects/*/locations/global/grpcRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, grpc_route.DeleteGrpcRouteRequest): + request = grpc_route.DeleteGrpcRouteRequest(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_grpc_route] + + # Certain 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_http_routes(self, + request: Optional[Union[http_route.ListHttpRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListHttpRoutesAsyncPager: + r"""Lists HttpRoute 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_services_v1 + + async def sample_list_http_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListHttpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_http_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListHttpRoutesRequest, dict]]): + The request object. Request used with the ListHttpRoutes + method. + parent (:class:`str`): + Required. The project and location from which the + HttpRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesAsyncPager: + Response returned by the + ListHttpRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, http_route.ListHttpRoutesRequest): + request = http_route.ListHttpRoutesRequest(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_http_routes] + + # 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.ListHttpRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_http_route(self, + request: Optional[Union[http_route.GetHttpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> http_route.HttpRoute: + r"""Gets details of a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetHttpRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_http_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetHttpRouteRequest, dict]]): + The request object. Request used by the GetHttpRoute + method. + name (:class:`str`): + Required. A name of the HttpRoute to get. Must be in the + format ``projects/*/locations/global/httpRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.HttpRoute: + HttpRoute is the resource defining + how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, http_route.GetHttpRouteRequest): + request = http_route.GetHttpRouteRequest(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_http_route] + + # Certain 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_http_route(self, + request: Optional[Union[gcn_http_route.CreateHttpRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + http_route: Optional[gcn_http_route.HttpRoute] = None, + http_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new HttpRoute 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_services_v1 + + async def sample_create_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateHttpRouteRequest( + parent="parent_value", + http_route_id="http_route_id_value", + http_route=http_route, + ) + + # Make the request + operation = client.create_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateHttpRouteRequest, dict]]): + The request object. Request used by the HttpRoute method. + parent (:class:`str`): + Required. The parent resource of the HttpRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + http_route (:class:`google.cloud.network_services_v1.types.HttpRoute`): + Required. HttpRoute resource to be + created. + + This corresponds to the ``http_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + http_route_id (:class:`str`): + Required. Short name of the HttpRoute + resource to be created. + + This corresponds to the ``http_route_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([parent, http_route, http_route_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_http_route.CreateHttpRouteRequest): + request = gcn_http_route.CreateHttpRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if http_route is not None: + request.http_route = http_route + if http_route_id is not None: + request.http_route_id = http_route_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_http_route] + + # 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_http_route.HttpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_http_route(self, + request: Optional[Union[gcn_http_route.UpdateHttpRouteRequest, dict]] = None, + *, + http_route: Optional[gcn_http_route.HttpRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateHttpRouteRequest( + http_route=http_route, + ) + + # Make the request + operation = client.update_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateHttpRouteRequest, dict]]): + The request object. Request used by the UpdateHttpRoute + method. + http_route (:class:`google.cloud.network_services_v1.types.HttpRoute`): + Required. Updated HttpRoute resource. + This corresponds to the ``http_route`` 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 HttpRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([http_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_http_route.UpdateHttpRouteRequest): + request = gcn_http_route.UpdateHttpRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if http_route is not None: + request.http_route = http_route + 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_http_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("http_route.name", request.http_route.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_http_route.HttpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_http_route(self, + request: Optional[Union[http_route.DeleteHttpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteHttpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteHttpRouteRequest, dict]]): + The request object. Request used by the DeleteHttpRoute + method. + name (:class:`str`): + Required. A name of the HttpRoute to delete. Must be in + the format ``projects/*/locations/global/httpRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, http_route.DeleteHttpRouteRequest): + request = http_route.DeleteHttpRouteRequest(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_http_route] + + # Certain 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_tcp_routes(self, + request: Optional[Union[tcp_route.ListTcpRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTcpRoutesAsyncPager: + r"""Lists TcpRoute 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_services_v1 + + async def sample_list_tcp_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListTcpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tcp_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListTcpRoutesRequest, dict]]): + The request object. Request used with the ListTcpRoutes + method. + parent (:class:`str`): + Required. The project and location from which the + TcpRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesAsyncPager: + Response returned by the + ListTcpRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tcp_route.ListTcpRoutesRequest): + request = tcp_route.ListTcpRoutesRequest(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_tcp_routes] + + # 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.ListTcpRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tcp_route(self, + request: Optional[Union[tcp_route.GetTcpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tcp_route.TcpRoute: + r"""Gets details of a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetTcpRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tcp_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetTcpRouteRequest, dict]]): + The request object. Request used by the GetTcpRoute + method. + name (:class:`str`): + Required. A name of the TcpRoute to get. Must be in the + format ``projects/*/locations/global/tcpRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.TcpRoute: + TcpRoute is the resource defining how + TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tcp_route.GetTcpRouteRequest): + request = tcp_route.GetTcpRouteRequest(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_tcp_route] + + # Certain 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_tcp_route(self, + request: Optional[Union[gcn_tcp_route.CreateTcpRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, + tcp_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new TcpRoute 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_services_v1 + + async def sample_create_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.CreateTcpRouteRequest( + parent="parent_value", + tcp_route_id="tcp_route_id_value", + tcp_route=tcp_route, + ) + + # Make the request + operation = client.create_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateTcpRouteRequest, dict]]): + The request object. Request used by the TcpRoute method. + parent (:class:`str`): + Required. The parent resource of the TcpRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tcp_route (:class:`google.cloud.network_services_v1.types.TcpRoute`): + Required. TcpRoute resource to be + created. + + This corresponds to the ``tcp_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tcp_route_id (:class:`str`): + Required. Short name of the TcpRoute + resource to be created. + + This corresponds to the ``tcp_route_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([parent, tcp_route, tcp_route_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_tcp_route.CreateTcpRouteRequest): + request = gcn_tcp_route.CreateTcpRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tcp_route is not None: + request.tcp_route = tcp_route + if tcp_route_id is not None: + request.tcp_route_id = tcp_route_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_tcp_route] + + # 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_tcp_route.TcpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_tcp_route(self, + request: Optional[Union[gcn_tcp_route.UpdateTcpRouteRequest, dict]] = None, + *, + tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.UpdateTcpRouteRequest( + tcp_route=tcp_route, + ) + + # Make the request + operation = client.update_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateTcpRouteRequest, dict]]): + The request object. Request used by the UpdateTcpRoute + method. + tcp_route (:class:`google.cloud.network_services_v1.types.TcpRoute`): + Required. Updated TcpRoute resource. + This corresponds to the ``tcp_route`` 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 TcpRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([tcp_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_tcp_route.UpdateTcpRouteRequest): + request = gcn_tcp_route.UpdateTcpRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tcp_route is not None: + request.tcp_route = tcp_route + 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_tcp_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tcp_route.name", request.tcp_route.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_tcp_route.TcpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_tcp_route(self, + request: Optional[Union[tcp_route.DeleteTcpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTcpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteTcpRouteRequest, dict]]): + The request object. Request used by the DeleteTcpRoute + method. + name (:class:`str`): + Required. A name of the TcpRoute to delete. Must be in + the format ``projects/*/locations/global/tcpRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tcp_route.DeleteTcpRouteRequest): + request = tcp_route.DeleteTcpRouteRequest(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_tcp_route] + + # Certain 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_tls_routes(self, + request: Optional[Union[tls_route.ListTlsRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTlsRoutesAsyncPager: + r"""Lists TlsRoute 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_services_v1 + + async def sample_list_tls_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListTlsRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tls_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListTlsRoutesRequest, dict]]): + The request object. Request used with the ListTlsRoutes + method. + parent (:class:`str`): + Required. The project and location from which the + TlsRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesAsyncPager: + Response returned by the + ListTlsRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tls_route.ListTlsRoutesRequest): + request = tls_route.ListTlsRoutesRequest(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_tls_routes] + + # 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.ListTlsRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tls_route(self, + request: Optional[Union[tls_route.GetTlsRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tls_route.TlsRoute: + r"""Gets details of a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetTlsRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tls_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetTlsRouteRequest, dict]]): + The request object. Request used by the GetTlsRoute + method. + name (:class:`str`): + Required. A name of the TlsRoute to get. Must be in the + format ``projects/*/locations/global/tlsRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.TlsRoute: + TlsRoute defines how traffic should + be routed based on SNI and other + matching L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tls_route.GetTlsRouteRequest): + request = tls_route.GetTlsRouteRequest(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_tls_route] + + # Certain 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_tls_route(self, + request: Optional[Union[gcn_tls_route.CreateTlsRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + tls_route: Optional[gcn_tls_route.TlsRoute] = None, + tls_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new TlsRoute 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_services_v1 + + async def sample_create_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.CreateTlsRouteRequest( + parent="parent_value", + tls_route_id="tls_route_id_value", + tls_route=tls_route, + ) + + # Make the request + operation = client.create_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateTlsRouteRequest, dict]]): + The request object. Request used by the TlsRoute method. + parent (:class:`str`): + Required. The parent resource of the TlsRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tls_route (:class:`google.cloud.network_services_v1.types.TlsRoute`): + Required. TlsRoute resource to be + created. + + This corresponds to the ``tls_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tls_route_id (:class:`str`): + Required. Short name of the TlsRoute + resource to be created. + + This corresponds to the ``tls_route_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching + L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, tls_route, tls_route_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_tls_route.CreateTlsRouteRequest): + request = gcn_tls_route.CreateTlsRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tls_route is not None: + request.tls_route = tls_route + if tls_route_id is not None: + request.tls_route_id = tls_route_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_tls_route] + + # 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_tls_route.TlsRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_tls_route(self, + request: Optional[Union[gcn_tls_route.UpdateTlsRouteRequest, dict]] = None, + *, + tls_route: Optional[gcn_tls_route.TlsRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.UpdateTlsRouteRequest( + tls_route=tls_route, + ) + + # Make the request + operation = client.update_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateTlsRouteRequest, dict]]): + The request object. Request used by the UpdateTlsRoute + method. + tls_route (:class:`google.cloud.network_services_v1.types.TlsRoute`): + Required. Updated TlsRoute resource. + This corresponds to the ``tls_route`` 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 TlsRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching + L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tls_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_tls_route.UpdateTlsRouteRequest): + request = gcn_tls_route.UpdateTlsRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tls_route is not None: + request.tls_route = tls_route + 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_tls_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tls_route.name", request.tls_route.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_tls_route.TlsRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_tls_route(self, + request: Optional[Union[tls_route.DeleteTlsRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTlsRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteTlsRouteRequest, dict]]): + The request object. Request used by the DeleteTlsRoute + method. + name (:class:`str`): + Required. A name of the TlsRoute to delete. Must be in + the format ``projects/*/locations/global/tlsRoutes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, tls_route.DeleteTlsRouteRequest): + request = tls_route.DeleteTlsRouteRequest(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_tls_route] + + # Certain 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_service_bindings(self, + request: Optional[Union[service_binding.ListServiceBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServiceBindingsAsyncPager: + r"""Lists ServiceBinding 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_services_v1 + + async def sample_list_service_bindings(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListServiceBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_service_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListServiceBindingsRequest, dict]]): + The request object. Request used with the + ListServiceBindings method. + parent (:class:`str`): + Required. The project and location from which the + ServiceBindings should be listed, specified in the + format ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsAsyncPager: + Response returned by the + ListServiceBindings 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, service_binding.ListServiceBindingsRequest): + request = service_binding.ListServiceBindingsRequest(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_service_bindings] + + # 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.ListServiceBindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service_binding(self, + request: Optional[Union[service_binding.GetServiceBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_binding.ServiceBinding: + r"""Gets details of a single ServiceBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetServiceBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetServiceBindingRequest, dict]]): + The request object. Request used by the GetServiceBinding + method. + name (:class:`str`): + Required. A name of the ServiceBinding to get. Must be + in the format + ``projects/*/locations/global/serviceBindings/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.ServiceBinding: + ServiceBinding is the resource that + defines a Service Directory Service to + be used in a BackendService 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, service_binding.GetServiceBindingRequest): + request = service_binding.GetServiceBindingRequest(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_service_binding] + + # Certain 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_service_binding(self, + request: Optional[Union[gcn_service_binding.CreateServiceBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + service_binding: Optional[gcn_service_binding.ServiceBinding] = None, + service_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ServiceBinding 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_services_v1 + + async def sample_create_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + service_binding = network_services_v1.ServiceBinding() + service_binding.name = "name_value" + service_binding.service = "service_value" + + request = network_services_v1.CreateServiceBindingRequest( + parent="parent_value", + service_binding_id="service_binding_id_value", + service_binding=service_binding, + ) + + # Make the request + operation = client.create_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateServiceBindingRequest, dict]]): + The request object. Request used by the ServiceBinding + method. + parent (:class:`str`): + Required. The parent resource of the ServiceBinding. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_binding (:class:`google.cloud.network_services_v1.types.ServiceBinding`): + Required. ServiceBinding resource to + be created. + + This corresponds to the ``service_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_binding_id (:class:`str`): + Required. Short name of the + ServiceBinding resource to be created. + + This corresponds to the ``service_binding_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.ServiceBinding` ServiceBinding is the resource that defines a Service Directory Service to + be used in a BackendService 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. + has_flattened_params = any([parent, service_binding, service_binding_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_service_binding.CreateServiceBindingRequest): + request = gcn_service_binding.CreateServiceBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service_binding is not None: + request.service_binding = service_binding + if service_binding_id is not None: + request.service_binding_id = service_binding_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_service_binding] + + # 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_service_binding.ServiceBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_service_binding(self, + request: Optional[Union[service_binding.DeleteServiceBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ServiceBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteServiceBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteServiceBindingRequest, dict]]): + The request object. Request used by the + DeleteServiceBinding method. + name (:class:`str`): + Required. A name of the ServiceBinding to delete. Must + be in the format + ``projects/*/locations/global/serviceBindings/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, service_binding.DeleteServiceBindingRequest): + request = service_binding.DeleteServiceBindingRequest(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_service_binding] + + # Certain 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_meshes(self, + request: Optional[Union[mesh.ListMeshesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMeshesAsyncPager: + r"""Lists Meshes 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_services_v1 + + async def sample_list_meshes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListMeshesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_meshes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.ListMeshesRequest, dict]]): + The request object. Request used with the ListMeshes + method. + parent (:class:`str`): + Required. The project and location from which the Meshes + should be listed, specified in the format + ``projects/*/locations/global``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListMeshesAsyncPager: + Response returned by the ListMeshes + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, mesh.ListMeshesRequest): + request = mesh.ListMeshesRequest(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_meshes] + + # 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.ListMeshesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_mesh(self, + request: Optional[Union[mesh.GetMeshRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mesh.Mesh: + r"""Gets details of a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_get_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetMeshRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mesh(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.GetMeshRequest, dict]]): + The request object. Request used by the GetMesh method. + name (:class:`str`): + Required. A name of the Mesh to get. Must be in the + format ``projects/*/locations/global/meshes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.Mesh: + Mesh represents a logical + configuration grouping for workload to + workload communication within a service + mesh. Routes that point to mesh dictate + how requests are routed within this + logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, mesh.GetMeshRequest): + request = mesh.GetMeshRequest(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_mesh] + + # Certain 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_mesh(self, + request: Optional[Union[gcn_mesh.CreateMeshRequest, dict]] = None, + *, + parent: Optional[str] = None, + mesh: Optional[gcn_mesh.Mesh] = None, + mesh_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Mesh 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_services_v1 + + async def sample_create_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.CreateMeshRequest( + parent="parent_value", + mesh_id="mesh_id_value", + mesh=mesh, + ) + + # Make the request + operation = client.create_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.CreateMeshRequest, dict]]): + The request object. Request used by the CreateMesh + method. + parent (:class:`str`): + Required. The parent resource of the Mesh. Must be in + the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mesh (:class:`google.cloud.network_services_v1.types.Mesh`): + Required. Mesh resource to be + created. + + This corresponds to the ``mesh`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mesh_id (:class:`str`): + Required. Short name of the Mesh + resource to be created. + + This corresponds to the ``mesh_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload + communication within a service mesh. Routes that + point to mesh dictate how requests are routed within + this logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mesh, mesh_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_mesh.CreateMeshRequest): + request = gcn_mesh.CreateMeshRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mesh is not None: + request.mesh = mesh + if mesh_id is not None: + request.mesh_id = mesh_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_mesh] + + # 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_mesh.Mesh, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_mesh(self, + request: Optional[Union[gcn_mesh.UpdateMeshRequest, dict]] = None, + *, + mesh: Optional[gcn_mesh.Mesh] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_update_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.UpdateMeshRequest( + mesh=mesh, + ) + + # Make the request + operation = client.update_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.UpdateMeshRequest, dict]]): + The request object. Request used by the UpdateMesh + method. + mesh (:class:`google.cloud.network_services_v1.types.Mesh`): + Required. Updated Mesh resource. + This corresponds to the ``mesh`` 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 Mesh 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload + communication within a service mesh. Routes that + point to mesh dictate how requests are routed within + this logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mesh, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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_mesh.UpdateMeshRequest): + request = gcn_mesh.UpdateMeshRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mesh is not None: + request.mesh = mesh + 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_mesh] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mesh.name", request.mesh.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_mesh.Mesh, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_mesh(self, + request: Optional[Union[mesh.DeleteMeshRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + async def sample_delete_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteMeshRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1.types.DeleteMeshRequest, dict]]): + The request object. Request used by the DeleteMesh + method. + name (:class:`str`): + Required. A name of the Mesh to delete. Must be in the + format ``projects/*/locations/global/meshes/*``. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, mesh.DeleteMeshRequest): + request = mesh.DeleteMeshRequest(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_mesh] + + # Certain 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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) -> "NetworkServicesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "NetworkServicesAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py new file mode 100644 index 000000000000..b406a45cb1b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py @@ -0,0 +1,6202 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_services_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, 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_services_v1.services.network_services import pagers +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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 NetworkServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import NetworkServicesGrpcTransport +from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .transports.rest import NetworkServicesRestTransport + + +class NetworkServicesClientMeta(type): + """Metaclass for the NetworkServices 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[NetworkServicesTransport]] + _transport_registry["grpc"] = NetworkServicesGrpcTransport + _transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkServicesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[NetworkServicesTransport]: + """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 NetworkServicesClient(metaclass=NetworkServicesClientMeta): + """""" + + @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 = "networkservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{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: + NetworkServicesClient: 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: + NetworkServicesClient: 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) -> NetworkServicesTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkServicesTransport: 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 backend_service_path(project: str,location: str,backend_service: str,) -> str: + """Returns a fully-qualified backend_service string.""" + return "projects/{project}/locations/{location}/backendServices/{backend_service}".format(project=project, location=location, backend_service=backend_service, ) + + @staticmethod + def parse_backend_service_path(path: str) -> Dict[str,str]: + """Parses a backend_service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/backendServices/(?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 endpoint_policy_path(project: str,location: str,endpoint_policy: str,) -> str: + """Returns a fully-qualified endpoint_policy string.""" + return "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format(project=project, location=location, endpoint_policy=endpoint_policy, ) + + @staticmethod + def parse_endpoint_policy_path(path: str) -> Dict[str,str]: + """Parses a endpoint_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/endpointPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def gateway_path(project: str,location: str,gateway: str,) -> str: + """Returns a fully-qualified gateway string.""" + return "projects/{project}/locations/{location}/gateways/{gateway}".format(project=project, location=location, gateway=gateway, ) + + @staticmethod + def parse_gateway_path(path: str) -> Dict[str,str]: + """Parses a gateway path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/gateways/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def grpc_route_path(project: str,location: str,grpc_route: str,) -> str: + """Returns a fully-qualified grpc_route string.""" + return "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format(project=project, location=location, grpc_route=grpc_route, ) + + @staticmethod + def parse_grpc_route_path(path: str) -> Dict[str,str]: + """Parses a grpc_route path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/grpcRoutes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def http_route_path(project: str,location: str,http_route: str,) -> str: + """Returns a fully-qualified http_route string.""" + return "projects/{project}/locations/{location}/httpRoutes/{http_route}".format(project=project, location=location, http_route=http_route, ) + + @staticmethod + def parse_http_route_path(path: str) -> Dict[str,str]: + """Parses a http_route path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/httpRoutes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def mesh_path(project: str,location: str,mesh: str,) -> str: + """Returns a fully-qualified mesh string.""" + return "projects/{project}/locations/{location}/meshes/{mesh}".format(project=project, location=location, mesh=mesh, ) + + @staticmethod + def parse_mesh_path(path: str) -> Dict[str,str]: + """Parses a mesh path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/meshes/(?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 service_binding_path(project: str,location: str,service_binding: str,) -> str: + """Returns a fully-qualified service_binding string.""" + return "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format(project=project, location=location, service_binding=service_binding, ) + + @staticmethod + def parse_service_binding_path(path: str) -> Dict[str,str]: + """Parses a service_binding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serviceBindings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tcp_route_path(project: str,location: str,tcp_route: str,) -> str: + """Returns a fully-qualified tcp_route string.""" + return "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format(project=project, location=location, tcp_route=tcp_route, ) + + @staticmethod + def parse_tcp_route_path(path: str) -> Dict[str,str]: + """Parses a tcp_route path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tcpRoutes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tls_route_path(project: str,location: str,tls_route: str,) -> str: + """Returns a fully-qualified tls_route string.""" + return "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format(project=project, location=location, tls_route=tls_route, ) + + @staticmethod + def parse_tls_route_path(path: str) -> Dict[str,str]: + """Parses a tls_route path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tlsRoutes/(?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 = NetworkServicesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NetworkServicesClient._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 = NetworkServicesClient._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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = NetworkServicesClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + 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. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + NetworkServicesClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @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, NetworkServicesTransport, Callable[..., NetworkServicesTransport]]] = 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 services 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,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): + 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 NetworkServicesTransport 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 = NetworkServicesClient._read_environment_variables() + self._client_cert_source = NetworkServicesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = NetworkServicesClient._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 + + 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, NetworkServicesTransport) + if transport_provided: + # transport is a NetworkServicesTransport 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(NetworkServicesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + NetworkServicesClient._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[NetworkServicesTransport], Callable[..., NetworkServicesTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NetworkServicesTransport], 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, + ) + + def list_endpoint_policies(self, + request: Optional[Union[endpoint_policy.ListEndpointPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointPoliciesPager: + r"""Lists EndpointPolicies 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_services_v1 + + def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListEndpointPoliciesRequest, dict]): + The request object. Request used with the + ListEndpointPolicies method. + parent (str): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the + format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesPager: + Response returned by the + ListEndpointPolicies 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, endpoint_policy.ListEndpointPoliciesRequest): + request = endpoint_policy.ListEndpointPoliciesRequest(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_endpoint_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.ListEndpointPoliciesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_endpoint_policy(self, + request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Gets details of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetEndpointPolicyRequest, dict]): + The request object. Request used with the + GetEndpointPolicy method. + name (str): + Required. A name of the EndpointPolicy to get. Must be + in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, endpoint_policy.GetEndpointPolicyRequest): + request = endpoint_policy.GetEndpointPolicyRequest(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_endpoint_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_endpoint_policy(self, + request: Optional[Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + endpoint_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new EndpointPolicy 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_services_v1 + + def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateEndpointPolicyRequest, dict]): + The request object. Request used with the + CreateEndpointPolicy method. + parent (str): + Required. The parent resource of the EndpointPolicy. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): + Required. EndpointPolicy resource to + be created. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy_id (str): + Required. Short name of the + EndpointPolicy resource to be created. + E.g. "CustomECS". + + This corresponds to the ``endpoint_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, endpoint_policy, endpoint_policy_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_endpoint_policy.CreateEndpointPolicyRequest): + request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if endpoint_policy_id is not None: + request.endpoint_policy_id = endpoint_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_endpoint_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_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_endpoint_policy(self, + request: Optional[Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict]] = None, + *, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest, dict]): + The request object. Request used with the + UpdateEndpointPolicy method. + endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): + Required. Updated EndpointPolicy + resource. + + This corresponds to the ``endpoint_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 EndpointPolicy 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint_policy, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_endpoint_policy.UpdateEndpointPolicyRequest): + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint_policy is not None: + request.endpoint_policy = endpoint_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_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("endpoint_policy.name", request.endpoint_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_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_endpoint_policy(self, + request: Optional[Union[endpoint_policy.DeleteEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest, dict]): + The request object. Request used with the + DeleteEndpointPolicy method. + name (str): + Required. A name of the EndpointPolicy to delete. Must + be in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, endpoint_policy.DeleteEndpointPolicyRequest): + request = endpoint_policy.DeleteEndpointPolicyRequest(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_endpoint_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_gateways(self, + request: Optional[Union[gateway.ListGatewaysRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGatewaysPager: + r"""Lists Gateways 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_services_v1 + + def sample_list_gateways(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListGatewaysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gateways(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListGatewaysRequest, dict]): + The request object. Request used with the ListGateways + method. + parent (str): + Required. The project and location from which the + Gateways should be listed, specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysPager: + Response returned by the ListGateways + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, gateway.ListGatewaysRequest): + request = gateway.ListGatewaysRequest(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_gateways] + + # 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.ListGatewaysPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_gateway(self, + request: Optional[Union[gateway.GetGatewayRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gateway.Gateway: + r"""Gets details of a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetGatewayRequest( + name="name_value", + ) + + # Make the request + response = client.get_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetGatewayRequest, dict]): + The request object. Request used by the GetGateway + method. + name (str): + Required. A name of the Gateway to get. Must be in the + format ``projects/*/locations/*/gateways/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.Gateway: + Gateway represents the configuration + for a proxy, typically a load balancer. + It captures the ip:port over which the + services are exposed by the proxy, along + with any policy configurations. Routes + have reference to to Gateways to dictate + how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, gateway.GetGatewayRequest): + request = gateway.GetGatewayRequest(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_gateway] + + # Certain 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_gateway(self, + request: Optional[Union[gcn_gateway.CreateGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway: Optional[gcn_gateway.Gateway] = None, + gateway_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Gateway 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_services_v1 + + def sample_create_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.CreateGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + gateway=gateway, + ) + + # Make the request + operation = client.create_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateGatewayRequest, dict]): + The request object. Request used by the CreateGateway + method. + parent (str): + Required. The parent resource of the Gateway. Must be in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway (google.cloud.network_services_v1.types.Gateway): + Required. Gateway resource to be + created. + + This corresponds to the ``gateway`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (str): + Required. Short name of the Gateway + resource to be created. + + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. + It captures the ip:port over which the services are + exposed by the proxy, along with any policy + configurations. Routes have reference to to Gateways + to dictate how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway, gateway_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_gateway.CreateGatewayRequest): + request = gcn_gateway.CreateGatewayRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway is not None: + request.gateway = gateway + if gateway_id is not None: + request.gateway_id = gateway_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_gateway] + + # 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_gateway.Gateway, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_gateway(self, + request: Optional[Union[gcn_gateway.UpdateGatewayRequest, dict]] = None, + *, + gateway: Optional[gcn_gateway.Gateway] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.UpdateGatewayRequest( + gateway=gateway, + ) + + # Make the request + operation = client.update_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateGatewayRequest, dict]): + The request object. Request used by the UpdateGateway + method. + gateway (google.cloud.network_services_v1.types.Gateway): + Required. Updated Gateway resource. + This corresponds to the ``gateway`` 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 Gateway 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. + It captures the ip:port over which the services are + exposed by the proxy, along with any policy + configurations. Routes have reference to to Gateways + to dictate how requests should be routed by this + Gateway. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([gateway, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_gateway.UpdateGatewayRequest): + request = gcn_gateway.UpdateGatewayRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if gateway is not None: + request.gateway = gateway + 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_gateway] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("gateway.name", request.gateway.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_gateway.Gateway, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_gateway(self, + request: Optional[Union[gateway.DeleteGatewayRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Gateway. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGatewayRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteGatewayRequest, dict]): + The request object. Request used by the DeleteGateway + method. + name (str): + Required. A name of the Gateway to delete. Must be in + the format ``projects/*/locations/*/gateways/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, gateway.DeleteGatewayRequest): + request = gateway.DeleteGatewayRequest(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_gateway] + + # Certain 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_grpc_routes(self, + request: Optional[Union[grpc_route.ListGrpcRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGrpcRoutesPager: + r"""Lists GrpcRoutes 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_services_v1 + + def sample_list_grpc_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListGrpcRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_grpc_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListGrpcRoutesRequest, dict]): + The request object. Request used with the ListGrpcRoutes + method. + parent (str): + Required. The project and location from which the + GrpcRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesPager: + Response returned by the + ListGrpcRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, grpc_route.ListGrpcRoutesRequest): + request = grpc_route.ListGrpcRoutesRequest(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_grpc_routes] + + # 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.ListGrpcRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_grpc_route(self, + request: Optional[Union[grpc_route.GetGrpcRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grpc_route.GrpcRoute: + r"""Gets details of a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetGrpcRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_grpc_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetGrpcRouteRequest, dict]): + The request object. Request used by the GetGrpcRoute + method. + name (str): + Required. A name of the GrpcRoute to get. Must be in the + format ``projects/*/locations/global/grpcRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.GrpcRoute: + GrpcRoute is the resource defining + how gRPC traffic routed by a Mesh or + Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, grpc_route.GetGrpcRouteRequest): + request = grpc_route.GetGrpcRouteRequest(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_grpc_route] + + # Certain 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_grpc_route(self, + request: Optional[Union[gcn_grpc_route.CreateGrpcRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, + grpc_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new GrpcRoute 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_services_v1 + + def sample_create_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateGrpcRouteRequest( + parent="parent_value", + grpc_route_id="grpc_route_id_value", + grpc_route=grpc_route, + ) + + # Make the request + operation = client.create_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateGrpcRouteRequest, dict]): + The request object. Request used by the CreateGrpcRoute + method. + parent (str): + Required. The parent resource of the GrpcRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + grpc_route (google.cloud.network_services_v1.types.GrpcRoute): + Required. GrpcRoute resource to be + created. + + This corresponds to the ``grpc_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + grpc_route_id (str): + Required. Short name of the GrpcRoute + resource to be created. + + This corresponds to the ``grpc_route_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh + or Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, grpc_route, grpc_route_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_grpc_route.CreateGrpcRouteRequest): + request = gcn_grpc_route.CreateGrpcRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if grpc_route is not None: + request.grpc_route = grpc_route + if grpc_route_id is not None: + request.grpc_route_id = grpc_route_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_grpc_route] + + # 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_grpc_route.GrpcRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_grpc_route(self, + request: Optional[Union[gcn_grpc_route.UpdateGrpcRouteRequest, dict]] = None, + *, + grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateGrpcRouteRequest( + grpc_route=grpc_route, + ) + + # Make the request + operation = client.update_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateGrpcRouteRequest, dict]): + The request object. Request used by the UpdateGrpcRoute + method. + grpc_route (google.cloud.network_services_v1.types.GrpcRoute): + Required. Updated GrpcRoute resource. + This corresponds to the ``grpc_route`` 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 GrpcRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh + or Gateway resource is routed. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([grpc_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_grpc_route.UpdateGrpcRouteRequest): + request = gcn_grpc_route.UpdateGrpcRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if grpc_route is not None: + request.grpc_route = grpc_route + 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_grpc_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("grpc_route.name", request.grpc_route.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_grpc_route.GrpcRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_grpc_route(self, + request: Optional[Union[grpc_route.DeleteGrpcRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single GrpcRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGrpcRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteGrpcRouteRequest, dict]): + The request object. Request used by the DeleteGrpcRoute + method. + name (str): + Required. A name of the GrpcRoute to delete. Must be in + the format ``projects/*/locations/global/grpcRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, grpc_route.DeleteGrpcRouteRequest): + request = grpc_route.DeleteGrpcRouteRequest(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_grpc_route] + + # Certain 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_http_routes(self, + request: Optional[Union[http_route.ListHttpRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListHttpRoutesPager: + r"""Lists HttpRoute 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_services_v1 + + def sample_list_http_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListHttpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_http_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListHttpRoutesRequest, dict]): + The request object. Request used with the ListHttpRoutes + method. + parent (str): + Required. The project and location from which the + HttpRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesPager: + Response returned by the + ListHttpRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, http_route.ListHttpRoutesRequest): + request = http_route.ListHttpRoutesRequest(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_http_routes] + + # 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.ListHttpRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_http_route(self, + request: Optional[Union[http_route.GetHttpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> http_route.HttpRoute: + r"""Gets details of a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetHttpRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_http_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetHttpRouteRequest, dict]): + The request object. Request used by the GetHttpRoute + method. + name (str): + Required. A name of the HttpRoute to get. Must be in the + format ``projects/*/locations/global/httpRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.HttpRoute: + HttpRoute is the resource defining + how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, http_route.GetHttpRouteRequest): + request = http_route.GetHttpRouteRequest(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_http_route] + + # Certain 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_http_route(self, + request: Optional[Union[gcn_http_route.CreateHttpRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + http_route: Optional[gcn_http_route.HttpRoute] = None, + http_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new HttpRoute 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_services_v1 + + def sample_create_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateHttpRouteRequest( + parent="parent_value", + http_route_id="http_route_id_value", + http_route=http_route, + ) + + # Make the request + operation = client.create_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateHttpRouteRequest, dict]): + The request object. Request used by the HttpRoute method. + parent (str): + Required. The parent resource of the HttpRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + http_route (google.cloud.network_services_v1.types.HttpRoute): + Required. HttpRoute resource to be + created. + + This corresponds to the ``http_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + http_route_id (str): + Required. Short name of the HttpRoute + resource to be created. + + This corresponds to the ``http_route_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([parent, http_route, http_route_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_http_route.CreateHttpRouteRequest): + request = gcn_http_route.CreateHttpRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if http_route is not None: + request.http_route = http_route + if http_route_id is not None: + request.http_route_id = http_route_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_http_route] + + # 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_http_route.HttpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_http_route(self, + request: Optional[Union[gcn_http_route.UpdateHttpRouteRequest, dict]] = None, + *, + http_route: Optional[gcn_http_route.HttpRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateHttpRouteRequest( + http_route=http_route, + ) + + # Make the request + operation = client.update_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateHttpRouteRequest, dict]): + The request object. Request used by the UpdateHttpRoute + method. + http_route (google.cloud.network_services_v1.types.HttpRoute): + Required. Updated HttpRoute resource. + This corresponds to the ``http_route`` 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 HttpRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a + Mesh or Gateway 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. + has_flattened_params = any([http_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_http_route.UpdateHttpRouteRequest): + request = gcn_http_route.UpdateHttpRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if http_route is not None: + request.http_route = http_route + 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_http_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("http_route.name", request.http_route.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_http_route.HttpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_http_route(self, + request: Optional[Union[http_route.DeleteHttpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single HttpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteHttpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteHttpRouteRequest, dict]): + The request object. Request used by the DeleteHttpRoute + method. + name (str): + Required. A name of the HttpRoute to delete. Must be in + the format ``projects/*/locations/global/httpRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, http_route.DeleteHttpRouteRequest): + request = http_route.DeleteHttpRouteRequest(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_http_route] + + # Certain 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_tcp_routes(self, + request: Optional[Union[tcp_route.ListTcpRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTcpRoutesPager: + r"""Lists TcpRoute 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_services_v1 + + def sample_list_tcp_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListTcpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tcp_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListTcpRoutesRequest, dict]): + The request object. Request used with the ListTcpRoutes + method. + parent (str): + Required. The project and location from which the + TcpRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesPager: + Response returned by the + ListTcpRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tcp_route.ListTcpRoutesRequest): + request = tcp_route.ListTcpRoutesRequest(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_tcp_routes] + + # 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.ListTcpRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tcp_route(self, + request: Optional[Union[tcp_route.GetTcpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tcp_route.TcpRoute: + r"""Gets details of a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetTcpRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_tcp_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetTcpRouteRequest, dict]): + The request object. Request used by the GetTcpRoute + method. + name (str): + Required. A name of the TcpRoute to get. Must be in the + format ``projects/*/locations/global/tcpRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.TcpRoute: + TcpRoute is the resource defining how + TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tcp_route.GetTcpRouteRequest): + request = tcp_route.GetTcpRouteRequest(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_tcp_route] + + # Certain 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_tcp_route(self, + request: Optional[Union[gcn_tcp_route.CreateTcpRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, + tcp_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new TcpRoute 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_services_v1 + + def sample_create_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.CreateTcpRouteRequest( + parent="parent_value", + tcp_route_id="tcp_route_id_value", + tcp_route=tcp_route, + ) + + # Make the request + operation = client.create_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateTcpRouteRequest, dict]): + The request object. Request used by the TcpRoute method. + parent (str): + Required. The parent resource of the TcpRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tcp_route (google.cloud.network_services_v1.types.TcpRoute): + Required. TcpRoute resource to be + created. + + This corresponds to the ``tcp_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tcp_route_id (str): + Required. Short name of the TcpRoute + resource to be created. + + This corresponds to the ``tcp_route_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([parent, tcp_route, tcp_route_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_tcp_route.CreateTcpRouteRequest): + request = gcn_tcp_route.CreateTcpRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tcp_route is not None: + request.tcp_route = tcp_route + if tcp_route_id is not None: + request.tcp_route_id = tcp_route_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tcp_route] + + # 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_tcp_route.TcpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_tcp_route(self, + request: Optional[Union[gcn_tcp_route.UpdateTcpRouteRequest, dict]] = None, + *, + tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.UpdateTcpRouteRequest( + tcp_route=tcp_route, + ) + + # Make the request + operation = client.update_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateTcpRouteRequest, dict]): + The request object. Request used by the UpdateTcpRoute + method. + tcp_route (google.cloud.network_services_v1.types.TcpRoute): + Required. Updated TcpRoute resource. + This corresponds to the ``tcp_route`` 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 TcpRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a + Mesh/Gateway 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. + has_flattened_params = any([tcp_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_tcp_route.UpdateTcpRouteRequest): + request = gcn_tcp_route.UpdateTcpRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tcp_route is not None: + request.tcp_route = tcp_route + 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_tcp_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tcp_route.name", request.tcp_route.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_tcp_route.TcpRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_tcp_route(self, + request: Optional[Union[tcp_route.DeleteTcpRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single TcpRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTcpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteTcpRouteRequest, dict]): + The request object. Request used by the DeleteTcpRoute + method. + name (str): + Required. A name of the TcpRoute to delete. Must be in + the format ``projects/*/locations/global/tcpRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tcp_route.DeleteTcpRouteRequest): + request = tcp_route.DeleteTcpRouteRequest(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_tcp_route] + + # Certain 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_tls_routes(self, + request: Optional[Union[tls_route.ListTlsRoutesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTlsRoutesPager: + r"""Lists TlsRoute 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_services_v1 + + def sample_list_tls_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListTlsRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tls_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListTlsRoutesRequest, dict]): + The request object. Request used with the ListTlsRoutes + method. + parent (str): + Required. The project and location from which the + TlsRoutes should be listed, specified in the format + ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesPager: + Response returned by the + ListTlsRoutes 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tls_route.ListTlsRoutesRequest): + request = tls_route.ListTlsRoutesRequest(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_tls_routes] + + # 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.ListTlsRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tls_route(self, + request: Optional[Union[tls_route.GetTlsRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tls_route.TlsRoute: + r"""Gets details of a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetTlsRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_tls_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetTlsRouteRequest, dict]): + The request object. Request used by the GetTlsRoute + method. + name (str): + Required. A name of the TlsRoute to get. Must be in the + format ``projects/*/locations/global/tlsRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.TlsRoute: + TlsRoute defines how traffic should + be routed based on SNI and other + matching L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tls_route.GetTlsRouteRequest): + request = tls_route.GetTlsRouteRequest(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_tls_route] + + # Certain 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_tls_route(self, + request: Optional[Union[gcn_tls_route.CreateTlsRouteRequest, dict]] = None, + *, + parent: Optional[str] = None, + tls_route: Optional[gcn_tls_route.TlsRoute] = None, + tls_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new TlsRoute 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_services_v1 + + def sample_create_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.CreateTlsRouteRequest( + parent="parent_value", + tls_route_id="tls_route_id_value", + tls_route=tls_route, + ) + + # Make the request + operation = client.create_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateTlsRouteRequest, dict]): + The request object. Request used by the TlsRoute method. + parent (str): + Required. The parent resource of the TlsRoute. Must be + in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tls_route (google.cloud.network_services_v1.types.TlsRoute): + Required. TlsRoute resource to be + created. + + This corresponds to the ``tls_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tls_route_id (str): + Required. Short name of the TlsRoute + resource to be created. + + This corresponds to the ``tls_route_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching + L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, tls_route, tls_route_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_tls_route.CreateTlsRouteRequest): + request = gcn_tls_route.CreateTlsRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tls_route is not None: + request.tls_route = tls_route + if tls_route_id is not None: + request.tls_route_id = tls_route_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tls_route] + + # 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_tls_route.TlsRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_tls_route(self, + request: Optional[Union[gcn_tls_route.UpdateTlsRouteRequest, dict]] = None, + *, + tls_route: Optional[gcn_tls_route.TlsRoute] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.UpdateTlsRouteRequest( + tls_route=tls_route, + ) + + # Make the request + operation = client.update_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateTlsRouteRequest, dict]): + The request object. Request used by the UpdateTlsRoute + method. + tls_route (google.cloud.network_services_v1.types.TlsRoute): + Required. Updated TlsRoute resource. + This corresponds to the ``tls_route`` 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 TlsRoute 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching + L3 attributes. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tls_route, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_tls_route.UpdateTlsRouteRequest): + request = gcn_tls_route.UpdateTlsRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tls_route is not None: + request.tls_route = tls_route + 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_tls_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tls_route.name", request.tls_route.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_tls_route.TlsRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_tls_route(self, + request: Optional[Union[tls_route.DeleteTlsRouteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single TlsRoute. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTlsRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteTlsRouteRequest, dict]): + The request object. Request used by the DeleteTlsRoute + method. + name (str): + Required. A name of the TlsRoute to delete. Must be in + the format ``projects/*/locations/global/tlsRoutes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, tls_route.DeleteTlsRouteRequest): + request = tls_route.DeleteTlsRouteRequest(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_tls_route] + + # Certain 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_service_bindings(self, + request: Optional[Union[service_binding.ListServiceBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServiceBindingsPager: + r"""Lists ServiceBinding 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_services_v1 + + def sample_list_service_bindings(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListServiceBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_service_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListServiceBindingsRequest, dict]): + The request object. Request used with the + ListServiceBindings method. + parent (str): + Required. The project and location from which the + ServiceBindings should be listed, specified in the + format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsPager: + Response returned by the + ListServiceBindings 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, service_binding.ListServiceBindingsRequest): + request = service_binding.ListServiceBindingsRequest(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_service_bindings] + + # 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.ListServiceBindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service_binding(self, + request: Optional[Union[service_binding.GetServiceBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_binding.ServiceBinding: + r"""Gets details of a single ServiceBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetServiceBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetServiceBindingRequest, dict]): + The request object. Request used by the GetServiceBinding + method. + name (str): + Required. A name of the ServiceBinding to get. Must be + in the format + ``projects/*/locations/global/serviceBindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.ServiceBinding: + ServiceBinding is the resource that + defines a Service Directory Service to + be used in a BackendService 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, service_binding.GetServiceBindingRequest): + request = service_binding.GetServiceBindingRequest(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_service_binding] + + # Certain 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_service_binding(self, + request: Optional[Union[gcn_service_binding.CreateServiceBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + service_binding: Optional[gcn_service_binding.ServiceBinding] = None, + service_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new ServiceBinding 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_services_v1 + + def sample_create_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + service_binding = network_services_v1.ServiceBinding() + service_binding.name = "name_value" + service_binding.service = "service_value" + + request = network_services_v1.CreateServiceBindingRequest( + parent="parent_value", + service_binding_id="service_binding_id_value", + service_binding=service_binding, + ) + + # Make the request + operation = client.create_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateServiceBindingRequest, dict]): + The request object. Request used by the ServiceBinding + method. + parent (str): + Required. The parent resource of the ServiceBinding. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_binding (google.cloud.network_services_v1.types.ServiceBinding): + Required. ServiceBinding resource to + be created. + + This corresponds to the ``service_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_binding_id (str): + Required. Short name of the + ServiceBinding resource to be created. + + This corresponds to the ``service_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.ServiceBinding` ServiceBinding is the resource that defines a Service Directory Service to + be used in a BackendService 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. + has_flattened_params = any([parent, service_binding, service_binding_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_service_binding.CreateServiceBindingRequest): + request = gcn_service_binding.CreateServiceBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service_binding is not None: + request.service_binding = service_binding + if service_binding_id is not None: + request.service_binding_id = service_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service_binding] + + # 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_service_binding.ServiceBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_service_binding(self, + request: Optional[Union[service_binding.DeleteServiceBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single ServiceBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteServiceBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteServiceBindingRequest, dict]): + The request object. Request used by the + DeleteServiceBinding method. + name (str): + Required. A name of the ServiceBinding to delete. Must + be in the format + ``projects/*/locations/global/serviceBindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, service_binding.DeleteServiceBindingRequest): + request = service_binding.DeleteServiceBindingRequest(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_service_binding] + + # Certain 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_meshes(self, + request: Optional[Union[mesh.ListMeshesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMeshesPager: + r"""Lists Meshes 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_services_v1 + + def sample_list_meshes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListMeshesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_meshes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.ListMeshesRequest, dict]): + The request object. Request used with the ListMeshes + method. + parent (str): + Required. The project and location from which the Meshes + should be listed, specified in the format + ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.services.network_services.pagers.ListMeshesPager: + Response returned by the ListMeshes + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, mesh.ListMeshesRequest): + request = mesh.ListMeshesRequest(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_meshes] + + # 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.ListMeshesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_mesh(self, + request: Optional[Union[mesh.GetMeshRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mesh.Mesh: + r"""Gets details of a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_get_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetMeshRequest( + name="name_value", + ) + + # Make the request + response = client.get_mesh(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.GetMeshRequest, dict]): + The request object. Request used by the GetMesh method. + name (str): + Required. A name of the Mesh to get. Must be in the + format ``projects/*/locations/global/meshes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.network_services_v1.types.Mesh: + Mesh represents a logical + configuration grouping for workload to + workload communication within a service + mesh. Routes that point to mesh dictate + how requests are routed within this + logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, mesh.GetMeshRequest): + request = mesh.GetMeshRequest(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_mesh] + + # Certain 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_mesh(self, + request: Optional[Union[gcn_mesh.CreateMeshRequest, dict]] = None, + *, + parent: Optional[str] = None, + mesh: Optional[gcn_mesh.Mesh] = None, + mesh_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Mesh 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_services_v1 + + def sample_create_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.CreateMeshRequest( + parent="parent_value", + mesh_id="mesh_id_value", + mesh=mesh, + ) + + # Make the request + operation = client.create_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.CreateMeshRequest, dict]): + The request object. Request used by the CreateMesh + method. + parent (str): + Required. The parent resource of the Mesh. Must be in + the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mesh (google.cloud.network_services_v1.types.Mesh): + Required. Mesh resource to be + created. + + This corresponds to the ``mesh`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mesh_id (str): + Required. Short name of the Mesh + resource to be created. + + This corresponds to the ``mesh_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload + communication within a service mesh. Routes that + point to mesh dictate how requests are routed within + this logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mesh, mesh_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_mesh.CreateMeshRequest): + request = gcn_mesh.CreateMeshRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mesh is not None: + request.mesh = mesh + if mesh_id is not None: + request.mesh_id = mesh_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mesh] + + # 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_mesh.Mesh, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_mesh(self, + request: Optional[Union[gcn_mesh.UpdateMeshRequest, dict]] = None, + *, + mesh: Optional[gcn_mesh.Mesh] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_update_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.UpdateMeshRequest( + mesh=mesh, + ) + + # Make the request + operation = client.update_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.UpdateMeshRequest, dict]): + The request object. Request used by the UpdateMesh + method. + mesh (google.cloud.network_services_v1.types.Mesh): + Required. Updated Mesh resource. + This corresponds to the ``mesh`` 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 Mesh 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload + communication within a service mesh. Routes that + point to mesh dictate how requests are routed within + this logical mesh boundary. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mesh, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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_mesh.UpdateMeshRequest): + request = gcn_mesh.UpdateMeshRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mesh is not None: + request.mesh = mesh + 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_mesh] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mesh.name", request.mesh.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_mesh.Mesh, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_mesh(self, + request: Optional[Union[mesh.DeleteMeshRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Mesh. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1 + + def sample_delete_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteMeshRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1.types.DeleteMeshRequest, dict]): + The request object. Request used by the DeleteMesh + method. + name (str): + Required. A name of the Mesh to delete. Must be in the + format ``projects/*/locations/global/meshes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, mesh.DeleteMeshRequest): + request = mesh.DeleteMeshRequest(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_mesh] + + # Certain 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) -> "NetworkServicesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # 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 get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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 + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "NetworkServicesClient", +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py new file mode 100644 index 000000000000..221631ee752d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py @@ -0,0 +1,993 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tls_route + + +class ListEndpointPoliciesPager: + """A pager for iterating through ``list_endpoint_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``endpoint_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEndpointPolicies`` requests and continue to iterate + through the ``endpoint_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` + 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[..., endpoint_policy.ListEndpointPoliciesResponse], + request: endpoint_policy.ListEndpointPoliciesRequest, + response: endpoint_policy.ListEndpointPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListEndpointPoliciesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListEndpointPoliciesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = endpoint_policy.ListEndpointPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[endpoint_policy.ListEndpointPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[endpoint_policy.EndpointPolicy]: + for page in self.pages: + yield from page.endpoint_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEndpointPoliciesAsyncPager: + """A pager for iterating through ``list_endpoint_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoint_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpointPolicies`` requests and continue to iterate + through the ``endpoint_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` + 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[endpoint_policy.ListEndpointPoliciesResponse]], + request: endpoint_policy.ListEndpointPoliciesRequest, + response: endpoint_policy.ListEndpointPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListEndpointPoliciesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListEndpointPoliciesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = endpoint_policy.ListEndpointPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[endpoint_policy.ListEndpointPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[endpoint_policy.EndpointPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoint_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGatewaysPager: + """A pager for iterating through ``list_gateways`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` object, and + provides an ``__iter__`` method to iterate through its + ``gateways`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGateways`` requests and continue to iterate + through the ``gateways`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` + 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[..., gateway.ListGatewaysResponse], + request: gateway.ListGatewaysRequest, + response: gateway.ListGatewaysResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListGatewaysRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListGatewaysResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = gateway.ListGatewaysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[gateway.ListGatewaysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[gateway.Gateway]: + for page in self.pages: + yield from page.gateways + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGatewaysAsyncPager: + """A pager for iterating through ``list_gateways`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``gateways`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGateways`` requests and continue to iterate + through the ``gateways`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` + 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[gateway.ListGatewaysResponse]], + request: gateway.ListGatewaysRequest, + response: gateway.ListGatewaysResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListGatewaysRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListGatewaysResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = gateway.ListGatewaysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[gateway.ListGatewaysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[gateway.Gateway]: + async def async_generator(): + async for page in self.pages: + for response in page.gateways: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGrpcRoutesPager: + """A pager for iterating through ``list_grpc_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``grpc_routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGrpcRoutes`` requests and continue to iterate + through the ``grpc_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` + 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[..., grpc_route.ListGrpcRoutesResponse], + request: grpc_route.ListGrpcRoutesRequest, + response: grpc_route.ListGrpcRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListGrpcRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListGrpcRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = grpc_route.ListGrpcRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[grpc_route.ListGrpcRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[grpc_route.GrpcRoute]: + for page in self.pages: + yield from page.grpc_routes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGrpcRoutesAsyncPager: + """A pager for iterating through ``list_grpc_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``grpc_routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGrpcRoutes`` requests and continue to iterate + through the ``grpc_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` + 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[grpc_route.ListGrpcRoutesResponse]], + request: grpc_route.ListGrpcRoutesRequest, + response: grpc_route.ListGrpcRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListGrpcRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListGrpcRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = grpc_route.ListGrpcRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[grpc_route.ListGrpcRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[grpc_route.GrpcRoute]: + async def async_generator(): + async for page in self.pages: + for response in page.grpc_routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListHttpRoutesPager: + """A pager for iterating through ``list_http_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``http_routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListHttpRoutes`` requests and continue to iterate + through the ``http_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` + 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[..., http_route.ListHttpRoutesResponse], + request: http_route.ListHttpRoutesRequest, + response: http_route.ListHttpRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListHttpRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListHttpRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = http_route.ListHttpRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[http_route.ListHttpRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[http_route.HttpRoute]: + for page in self.pages: + yield from page.http_routes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListHttpRoutesAsyncPager: + """A pager for iterating through ``list_http_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``http_routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListHttpRoutes`` requests and continue to iterate + through the ``http_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` + 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[http_route.ListHttpRoutesResponse]], + request: http_route.ListHttpRoutesRequest, + response: http_route.ListHttpRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListHttpRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListHttpRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = http_route.ListHttpRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[http_route.ListHttpRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[http_route.HttpRoute]: + async def async_generator(): + async for page in self.pages: + for response in page.http_routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTcpRoutesPager: + """A pager for iterating through ``list_tcp_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tcp_routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTcpRoutes`` requests and continue to iterate + through the ``tcp_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` + 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[..., tcp_route.ListTcpRoutesResponse], + request: tcp_route.ListTcpRoutesRequest, + response: tcp_route.ListTcpRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListTcpRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListTcpRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tcp_route.ListTcpRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tcp_route.ListTcpRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tcp_route.TcpRoute]: + for page in self.pages: + yield from page.tcp_routes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTcpRoutesAsyncPager: + """A pager for iterating through ``list_tcp_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tcp_routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTcpRoutes`` requests and continue to iterate + through the ``tcp_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` + 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[tcp_route.ListTcpRoutesResponse]], + request: tcp_route.ListTcpRoutesRequest, + response: tcp_route.ListTcpRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListTcpRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListTcpRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tcp_route.ListTcpRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tcp_route.ListTcpRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[tcp_route.TcpRoute]: + async def async_generator(): + async for page in self.pages: + for response in page.tcp_routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTlsRoutesPager: + """A pager for iterating through ``list_tls_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tls_routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTlsRoutes`` requests and continue to iterate + through the ``tls_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` + 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[..., tls_route.ListTlsRoutesResponse], + request: tls_route.ListTlsRoutesRequest, + response: tls_route.ListTlsRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListTlsRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListTlsRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tls_route.ListTlsRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tls_route.ListTlsRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tls_route.TlsRoute]: + for page in self.pages: + yield from page.tls_routes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTlsRoutesAsyncPager: + """A pager for iterating through ``list_tls_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tls_routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTlsRoutes`` requests and continue to iterate + through the ``tls_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` + 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[tls_route.ListTlsRoutesResponse]], + request: tls_route.ListTlsRoutesRequest, + response: tls_route.ListTlsRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListTlsRoutesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListTlsRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tls_route.ListTlsRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tls_route.ListTlsRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[tls_route.TlsRoute]: + async def async_generator(): + async for page in self.pages: + for response in page.tls_routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServiceBindingsPager: + """A pager for iterating through ``list_service_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``service_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServiceBindings`` requests and continue to iterate + through the ``service_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` + 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[..., service_binding.ListServiceBindingsResponse], + request: service_binding.ListServiceBindingsRequest, + response: service_binding.ListServiceBindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListServiceBindingsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListServiceBindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service_binding.ListServiceBindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service_binding.ListServiceBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[service_binding.ServiceBinding]: + for page in self.pages: + yield from page.service_bindings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServiceBindingsAsyncPager: + """A pager for iterating through ``list_service_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``service_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServiceBindings`` requests and continue to iterate + through the ``service_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` + 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[service_binding.ListServiceBindingsResponse]], + request: service_binding.ListServiceBindingsRequest, + response: service_binding.ListServiceBindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListServiceBindingsRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListServiceBindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service_binding.ListServiceBindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service_binding.ListServiceBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[service_binding.ServiceBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.service_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeshesPager: + """A pager for iterating through ``list_meshes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListMeshesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``meshes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMeshes`` requests and continue to iterate + through the ``meshes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListMeshesResponse` + 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[..., mesh.ListMeshesResponse], + request: mesh.ListMeshesRequest, + response: mesh.ListMeshesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListMeshesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListMeshesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = mesh.ListMeshesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[mesh.ListMeshesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[mesh.Mesh]: + for page in self.pages: + yield from page.meshes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeshesAsyncPager: + """A pager for iterating through ``list_meshes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1.types.ListMeshesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``meshes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMeshes`` requests and continue to iterate + through the ``meshes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1.types.ListMeshesResponse` + 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[mesh.ListMeshesResponse]], + request: mesh.ListMeshesRequest, + response: mesh.ListMeshesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1.types.ListMeshesRequest): + The initial request object. + response (google.cloud.network_services_v1.types.ListMeshesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = mesh.ListMeshesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[mesh.ListMeshesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[mesh.Mesh]: + async def async_generator(): + async for page in self.pages: + for response in page.meshes: + 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-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py new file mode 100644 index 000000000000..44d166b35e75 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 NetworkServicesTransport +from .grpc import NetworkServicesGrpcTransport +from .grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .rest import NetworkServicesRestTransport +from .rest import NetworkServicesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkServicesTransport]] +_transport_registry['grpc'] = NetworkServicesGrpcTransport +_transport_registry['grpc_asyncio'] = NetworkServicesGrpcAsyncIOTransport +_transport_registry['rest'] = NetworkServicesRestTransport + +__all__ = ( + 'NetworkServicesTransport', + 'NetworkServicesGrpcTransport', + 'NetworkServicesGrpcAsyncIOTransport', + 'NetworkServicesRestTransport', + 'NetworkServicesRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py new file mode 100644 index 000000000000..21230f51ded9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py @@ -0,0 +1,791 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_services_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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__) + + +class NetworkServicesTransport(abc.ABC): + """Abstract transport class for NetworkServices.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networkservices.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: 'networkservices.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 no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_endpoint_policies: gapic_v1.method.wrap_method( + self.list_endpoint_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint_policy: gapic_v1.method.wrap_method( + self.get_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint_policy: gapic_v1.method.wrap_method( + self.create_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint_policy: gapic_v1.method.wrap_method( + self.update_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint_policy: gapic_v1.method.wrap_method( + self.delete_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_gateways: gapic_v1.method.wrap_method( + self.list_gateways, + default_timeout=None, + client_info=client_info, + ), + self.get_gateway: gapic_v1.method.wrap_method( + self.get_gateway, + default_timeout=None, + client_info=client_info, + ), + self.create_gateway: gapic_v1.method.wrap_method( + self.create_gateway, + default_timeout=None, + client_info=client_info, + ), + self.update_gateway: gapic_v1.method.wrap_method( + self.update_gateway, + default_timeout=None, + client_info=client_info, + ), + self.delete_gateway: gapic_v1.method.wrap_method( + self.delete_gateway, + default_timeout=None, + client_info=client_info, + ), + self.list_grpc_routes: gapic_v1.method.wrap_method( + self.list_grpc_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_grpc_route: gapic_v1.method.wrap_method( + self.get_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.create_grpc_route: gapic_v1.method.wrap_method( + self.create_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.update_grpc_route: gapic_v1.method.wrap_method( + self.update_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_grpc_route: gapic_v1.method.wrap_method( + self.delete_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.list_http_routes: gapic_v1.method.wrap_method( + self.list_http_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_http_route: gapic_v1.method.wrap_method( + self.get_http_route, + default_timeout=None, + client_info=client_info, + ), + self.create_http_route: gapic_v1.method.wrap_method( + self.create_http_route, + default_timeout=None, + client_info=client_info, + ), + self.update_http_route: gapic_v1.method.wrap_method( + self.update_http_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_http_route: gapic_v1.method.wrap_method( + self.delete_http_route, + default_timeout=None, + client_info=client_info, + ), + self.list_tcp_routes: gapic_v1.method.wrap_method( + self.list_tcp_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_tcp_route: gapic_v1.method.wrap_method( + self.get_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.create_tcp_route: gapic_v1.method.wrap_method( + self.create_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.update_tcp_route: gapic_v1.method.wrap_method( + self.update_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_tcp_route: gapic_v1.method.wrap_method( + self.delete_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.list_tls_routes: gapic_v1.method.wrap_method( + self.list_tls_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_tls_route: gapic_v1.method.wrap_method( + self.get_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.create_tls_route: gapic_v1.method.wrap_method( + self.create_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.update_tls_route: gapic_v1.method.wrap_method( + self.update_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_tls_route: gapic_v1.method.wrap_method( + self.delete_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.list_service_bindings: gapic_v1.method.wrap_method( + self.list_service_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_service_binding: gapic_v1.method.wrap_method( + self.get_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_service_binding: gapic_v1.method.wrap_method( + self.create_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_binding: gapic_v1.method.wrap_method( + self.delete_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_meshes: gapic_v1.method.wrap_method( + self.list_meshes, + default_timeout=None, + client_info=client_info, + ), + self.get_mesh: gapic_v1.method.wrap_method( + self.get_mesh, + default_timeout=None, + client_info=client_info, + ), + self.create_mesh: gapic_v1.method.wrap_method( + self.create_mesh, + default_timeout=None, + client_info=client_info, + ), + self.update_mesh: gapic_v1.method.wrap_method( + self.update_mesh, + default_timeout=None, + client_info=client_info, + ), + self.delete_mesh: gapic_v1.method.wrap_method( + self.delete_mesh, + 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_endpoint_policies(self) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + Union[ + endpoint_policy.ListEndpointPoliciesResponse, + Awaitable[endpoint_policy.ListEndpointPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_endpoint_policy(self) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + Union[ + endpoint_policy.EndpointPolicy, + Awaitable[endpoint_policy.EndpointPolicy] + ]]: + raise NotImplementedError() + + @property + def create_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_endpoint_policy(self) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_gateways(self) -> Callable[ + [gateway.ListGatewaysRequest], + Union[ + gateway.ListGatewaysResponse, + Awaitable[gateway.ListGatewaysResponse] + ]]: + raise NotImplementedError() + + @property + def get_gateway(self) -> Callable[ + [gateway.GetGatewayRequest], + Union[ + gateway.Gateway, + Awaitable[gateway.Gateway] + ]]: + raise NotImplementedError() + + @property + def create_gateway(self) -> Callable[ + [gcn_gateway.CreateGatewayRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_gateway(self) -> Callable[ + [gcn_gateway.UpdateGatewayRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_gateway(self) -> Callable[ + [gateway.DeleteGatewayRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_grpc_routes(self) -> Callable[ + [grpc_route.ListGrpcRoutesRequest], + Union[ + grpc_route.ListGrpcRoutesResponse, + Awaitable[grpc_route.ListGrpcRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def get_grpc_route(self) -> Callable[ + [grpc_route.GetGrpcRouteRequest], + Union[ + grpc_route.GrpcRoute, + Awaitable[grpc_route.GrpcRoute] + ]]: + raise NotImplementedError() + + @property + def create_grpc_route(self) -> Callable[ + [gcn_grpc_route.CreateGrpcRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_grpc_route(self) -> Callable[ + [gcn_grpc_route.UpdateGrpcRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_grpc_route(self) -> Callable[ + [grpc_route.DeleteGrpcRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_http_routes(self) -> Callable[ + [http_route.ListHttpRoutesRequest], + Union[ + http_route.ListHttpRoutesResponse, + Awaitable[http_route.ListHttpRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def get_http_route(self) -> Callable[ + [http_route.GetHttpRouteRequest], + Union[ + http_route.HttpRoute, + Awaitable[http_route.HttpRoute] + ]]: + raise NotImplementedError() + + @property + def create_http_route(self) -> Callable[ + [gcn_http_route.CreateHttpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_http_route(self) -> Callable[ + [gcn_http_route.UpdateHttpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_http_route(self) -> Callable[ + [http_route.DeleteHttpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_tcp_routes(self) -> Callable[ + [tcp_route.ListTcpRoutesRequest], + Union[ + tcp_route.ListTcpRoutesResponse, + Awaitable[tcp_route.ListTcpRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def get_tcp_route(self) -> Callable[ + [tcp_route.GetTcpRouteRequest], + Union[ + tcp_route.TcpRoute, + Awaitable[tcp_route.TcpRoute] + ]]: + raise NotImplementedError() + + @property + def create_tcp_route(self) -> Callable[ + [gcn_tcp_route.CreateTcpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_tcp_route(self) -> Callable[ + [gcn_tcp_route.UpdateTcpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_tcp_route(self) -> Callable[ + [tcp_route.DeleteTcpRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_tls_routes(self) -> Callable[ + [tls_route.ListTlsRoutesRequest], + Union[ + tls_route.ListTlsRoutesResponse, + Awaitable[tls_route.ListTlsRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def get_tls_route(self) -> Callable[ + [tls_route.GetTlsRouteRequest], + Union[ + tls_route.TlsRoute, + Awaitable[tls_route.TlsRoute] + ]]: + raise NotImplementedError() + + @property + def create_tls_route(self) -> Callable[ + [gcn_tls_route.CreateTlsRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_tls_route(self) -> Callable[ + [gcn_tls_route.UpdateTlsRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_tls_route(self) -> Callable[ + [tls_route.DeleteTlsRouteRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_service_bindings(self) -> Callable[ + [service_binding.ListServiceBindingsRequest], + Union[ + service_binding.ListServiceBindingsResponse, + Awaitable[service_binding.ListServiceBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def get_service_binding(self) -> Callable[ + [service_binding.GetServiceBindingRequest], + Union[ + service_binding.ServiceBinding, + Awaitable[service_binding.ServiceBinding] + ]]: + raise NotImplementedError() + + @property + def create_service_binding(self) -> Callable[ + [gcn_service_binding.CreateServiceBindingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service_binding(self) -> Callable[ + [service_binding.DeleteServiceBindingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_meshes(self) -> Callable[ + [mesh.ListMeshesRequest], + Union[ + mesh.ListMeshesResponse, + Awaitable[mesh.ListMeshesResponse] + ]]: + raise NotImplementedError() + + @property + def get_mesh(self) -> Callable[ + [mesh.GetMeshRequest], + Union[ + mesh.Mesh, + Awaitable[mesh.Mesh] + ]]: + raise NotImplementedError() + + @property + def create_mesh(self) -> Callable[ + [gcn_mesh.CreateMeshRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_mesh(self) -> Callable[ + [gcn_mesh.UpdateMeshRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_mesh(self) -> Callable[ + [mesh.DeleteMeshRequest], + 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__ = ( + 'NetworkServicesTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py new file mode 100644 index 000000000000..4065be859d2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py @@ -0,0 +1,1487 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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 NetworkServicesTransport, DEFAULT_CLIENT_INFO + + +class NetworkServicesGrpcTransport(NetworkServicesTransport): + """gRPC backend transport for NetworkServices. + + 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 = 'networkservices.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: 'networkservices.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 = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networkservices.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_endpoint_policies(self) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + endpoint_policy.ListEndpointPoliciesResponse]: + r"""Return a callable for the list endpoint policies method over gRPC. + + Lists EndpointPolicies in a given project and + location. + + Returns: + Callable[[~.ListEndpointPoliciesRequest], + ~.ListEndpointPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint_policies' not in self._stubs: + self._stubs['list_endpoint_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListEndpointPolicies', + request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, + response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, + ) + return self._stubs['list_endpoint_policies'] + + @property + def get_endpoint_policy(self) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + endpoint_policy.EndpointPolicy]: + r"""Return a callable for the get endpoint policy method over gRPC. + + Gets details of a single EndpointPolicy. + + Returns: + Callable[[~.GetEndpointPolicyRequest], + ~.EndpointPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint_policy' not in self._stubs: + self._stubs['get_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetEndpointPolicy', + request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, + response_deserializer=endpoint_policy.EndpointPolicy.deserialize, + ) + return self._stubs['get_endpoint_policy'] + + @property + def create_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create endpoint policy method over gRPC. + + Creates a new EndpointPolicy in a given project and + location. + + Returns: + Callable[[~.CreateEndpointPolicyRequest], + ~.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_endpoint_policy' not in self._stubs: + self._stubs['create_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateEndpointPolicy', + request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_endpoint_policy'] + + @property + def update_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update endpoint policy method over gRPC. + + Updates the parameters of a single EndpointPolicy. + + Returns: + Callable[[~.UpdateEndpointPolicyRequest], + ~.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_endpoint_policy' not in self._stubs: + self._stubs['update_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateEndpointPolicy', + request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_endpoint_policy'] + + @property + def delete_endpoint_policy(self) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete endpoint policy method over gRPC. + + Deletes a single EndpointPolicy. + + Returns: + Callable[[~.DeleteEndpointPolicyRequest], + ~.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_endpoint_policy' not in self._stubs: + self._stubs['delete_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteEndpointPolicy', + request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_endpoint_policy'] + + @property + def list_gateways(self) -> Callable[ + [gateway.ListGatewaysRequest], + gateway.ListGatewaysResponse]: + r"""Return a callable for the list gateways method over gRPC. + + Lists Gateways in a given project and location. + + Returns: + Callable[[~.ListGatewaysRequest], + ~.ListGatewaysResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_gateways' not in self._stubs: + self._stubs['list_gateways'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListGateways', + request_serializer=gateway.ListGatewaysRequest.serialize, + response_deserializer=gateway.ListGatewaysResponse.deserialize, + ) + return self._stubs['list_gateways'] + + @property + def get_gateway(self) -> Callable[ + [gateway.GetGatewayRequest], + gateway.Gateway]: + r"""Return a callable for the get gateway method over gRPC. + + Gets details of a single Gateway. + + Returns: + Callable[[~.GetGatewayRequest], + ~.Gateway]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_gateway' not in self._stubs: + self._stubs['get_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetGateway', + request_serializer=gateway.GetGatewayRequest.serialize, + response_deserializer=gateway.Gateway.deserialize, + ) + return self._stubs['get_gateway'] + + @property + def create_gateway(self) -> Callable[ + [gcn_gateway.CreateGatewayRequest], + operations_pb2.Operation]: + r"""Return a callable for the create gateway method over gRPC. + + Creates a new Gateway in a given project and + location. + + Returns: + Callable[[~.CreateGatewayRequest], + ~.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_gateway' not in self._stubs: + self._stubs['create_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateGateway', + request_serializer=gcn_gateway.CreateGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_gateway'] + + @property + def update_gateway(self) -> Callable[ + [gcn_gateway.UpdateGatewayRequest], + operations_pb2.Operation]: + r"""Return a callable for the update gateway method over gRPC. + + Updates the parameters of a single Gateway. + + Returns: + Callable[[~.UpdateGatewayRequest], + ~.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_gateway' not in self._stubs: + self._stubs['update_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateGateway', + request_serializer=gcn_gateway.UpdateGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_gateway'] + + @property + def delete_gateway(self) -> Callable[ + [gateway.DeleteGatewayRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete gateway method over gRPC. + + Deletes a single Gateway. + + Returns: + Callable[[~.DeleteGatewayRequest], + ~.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_gateway' not in self._stubs: + self._stubs['delete_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteGateway', + request_serializer=gateway.DeleteGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_gateway'] + + @property + def list_grpc_routes(self) -> Callable[ + [grpc_route.ListGrpcRoutesRequest], + grpc_route.ListGrpcRoutesResponse]: + r"""Return a callable for the list grpc routes method over gRPC. + + Lists GrpcRoutes in a given project and location. + + Returns: + Callable[[~.ListGrpcRoutesRequest], + ~.ListGrpcRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_grpc_routes' not in self._stubs: + self._stubs['list_grpc_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListGrpcRoutes', + request_serializer=grpc_route.ListGrpcRoutesRequest.serialize, + response_deserializer=grpc_route.ListGrpcRoutesResponse.deserialize, + ) + return self._stubs['list_grpc_routes'] + + @property + def get_grpc_route(self) -> Callable[ + [grpc_route.GetGrpcRouteRequest], + grpc_route.GrpcRoute]: + r"""Return a callable for the get grpc route method over gRPC. + + Gets details of a single GrpcRoute. + + Returns: + Callable[[~.GetGrpcRouteRequest], + ~.GrpcRoute]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_grpc_route' not in self._stubs: + self._stubs['get_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetGrpcRoute', + request_serializer=grpc_route.GetGrpcRouteRequest.serialize, + response_deserializer=grpc_route.GrpcRoute.deserialize, + ) + return self._stubs['get_grpc_route'] + + @property + def create_grpc_route(self) -> Callable[ + [gcn_grpc_route.CreateGrpcRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the create grpc route method over gRPC. + + Creates a new GrpcRoute in a given project and + location. + + Returns: + Callable[[~.CreateGrpcRouteRequest], + ~.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_grpc_route' not in self._stubs: + self._stubs['create_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateGrpcRoute', + request_serializer=gcn_grpc_route.CreateGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_grpc_route'] + + @property + def update_grpc_route(self) -> Callable[ + [gcn_grpc_route.UpdateGrpcRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the update grpc route method over gRPC. + + Updates the parameters of a single GrpcRoute. + + Returns: + Callable[[~.UpdateGrpcRouteRequest], + ~.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_grpc_route' not in self._stubs: + self._stubs['update_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateGrpcRoute', + request_serializer=gcn_grpc_route.UpdateGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_grpc_route'] + + @property + def delete_grpc_route(self) -> Callable[ + [grpc_route.DeleteGrpcRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete grpc route method over gRPC. + + Deletes a single GrpcRoute. + + Returns: + Callable[[~.DeleteGrpcRouteRequest], + ~.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_grpc_route' not in self._stubs: + self._stubs['delete_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteGrpcRoute', + request_serializer=grpc_route.DeleteGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_grpc_route'] + + @property + def list_http_routes(self) -> Callable[ + [http_route.ListHttpRoutesRequest], + http_route.ListHttpRoutesResponse]: + r"""Return a callable for the list http routes method over gRPC. + + Lists HttpRoute in a given project and location. + + Returns: + Callable[[~.ListHttpRoutesRequest], + ~.ListHttpRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_http_routes' not in self._stubs: + self._stubs['list_http_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListHttpRoutes', + request_serializer=http_route.ListHttpRoutesRequest.serialize, + response_deserializer=http_route.ListHttpRoutesResponse.deserialize, + ) + return self._stubs['list_http_routes'] + + @property + def get_http_route(self) -> Callable[ + [http_route.GetHttpRouteRequest], + http_route.HttpRoute]: + r"""Return a callable for the get http route method over gRPC. + + Gets details of a single HttpRoute. + + Returns: + Callable[[~.GetHttpRouteRequest], + ~.HttpRoute]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_http_route' not in self._stubs: + self._stubs['get_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetHttpRoute', + request_serializer=http_route.GetHttpRouteRequest.serialize, + response_deserializer=http_route.HttpRoute.deserialize, + ) + return self._stubs['get_http_route'] + + @property + def create_http_route(self) -> Callable[ + [gcn_http_route.CreateHttpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the create http route method over gRPC. + + Creates a new HttpRoute in a given project and + location. + + Returns: + Callable[[~.CreateHttpRouteRequest], + ~.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_http_route' not in self._stubs: + self._stubs['create_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateHttpRoute', + request_serializer=gcn_http_route.CreateHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_http_route'] + + @property + def update_http_route(self) -> Callable[ + [gcn_http_route.UpdateHttpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the update http route method over gRPC. + + Updates the parameters of a single HttpRoute. + + Returns: + Callable[[~.UpdateHttpRouteRequest], + ~.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_http_route' not in self._stubs: + self._stubs['update_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateHttpRoute', + request_serializer=gcn_http_route.UpdateHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_http_route'] + + @property + def delete_http_route(self) -> Callable[ + [http_route.DeleteHttpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete http route method over gRPC. + + Deletes a single HttpRoute. + + Returns: + Callable[[~.DeleteHttpRouteRequest], + ~.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_http_route' not in self._stubs: + self._stubs['delete_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteHttpRoute', + request_serializer=http_route.DeleteHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_http_route'] + + @property + def list_tcp_routes(self) -> Callable[ + [tcp_route.ListTcpRoutesRequest], + tcp_route.ListTcpRoutesResponse]: + r"""Return a callable for the list tcp routes method over gRPC. + + Lists TcpRoute in a given project and location. + + Returns: + Callable[[~.ListTcpRoutesRequest], + ~.ListTcpRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tcp_routes' not in self._stubs: + self._stubs['list_tcp_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListTcpRoutes', + request_serializer=tcp_route.ListTcpRoutesRequest.serialize, + response_deserializer=tcp_route.ListTcpRoutesResponse.deserialize, + ) + return self._stubs['list_tcp_routes'] + + @property + def get_tcp_route(self) -> Callable[ + [tcp_route.GetTcpRouteRequest], + tcp_route.TcpRoute]: + r"""Return a callable for the get tcp route method over gRPC. + + Gets details of a single TcpRoute. + + Returns: + Callable[[~.GetTcpRouteRequest], + ~.TcpRoute]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tcp_route' not in self._stubs: + self._stubs['get_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetTcpRoute', + request_serializer=tcp_route.GetTcpRouteRequest.serialize, + response_deserializer=tcp_route.TcpRoute.deserialize, + ) + return self._stubs['get_tcp_route'] + + @property + def create_tcp_route(self) -> Callable[ + [gcn_tcp_route.CreateTcpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the create tcp route method over gRPC. + + Creates a new TcpRoute in a given project and + location. + + Returns: + Callable[[~.CreateTcpRouteRequest], + ~.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_tcp_route' not in self._stubs: + self._stubs['create_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateTcpRoute', + request_serializer=gcn_tcp_route.CreateTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tcp_route'] + + @property + def update_tcp_route(self) -> Callable[ + [gcn_tcp_route.UpdateTcpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the update tcp route method over gRPC. + + Updates the parameters of a single TcpRoute. + + Returns: + Callable[[~.UpdateTcpRouteRequest], + ~.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_tcp_route' not in self._stubs: + self._stubs['update_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateTcpRoute', + request_serializer=gcn_tcp_route.UpdateTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tcp_route'] + + @property + def delete_tcp_route(self) -> Callable[ + [tcp_route.DeleteTcpRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete tcp route method over gRPC. + + Deletes a single TcpRoute. + + Returns: + Callable[[~.DeleteTcpRouteRequest], + ~.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_tcp_route' not in self._stubs: + self._stubs['delete_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteTcpRoute', + request_serializer=tcp_route.DeleteTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tcp_route'] + + @property + def list_tls_routes(self) -> Callable[ + [tls_route.ListTlsRoutesRequest], + tls_route.ListTlsRoutesResponse]: + r"""Return a callable for the list tls routes method over gRPC. + + Lists TlsRoute in a given project and location. + + Returns: + Callable[[~.ListTlsRoutesRequest], + ~.ListTlsRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tls_routes' not in self._stubs: + self._stubs['list_tls_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListTlsRoutes', + request_serializer=tls_route.ListTlsRoutesRequest.serialize, + response_deserializer=tls_route.ListTlsRoutesResponse.deserialize, + ) + return self._stubs['list_tls_routes'] + + @property + def get_tls_route(self) -> Callable[ + [tls_route.GetTlsRouteRequest], + tls_route.TlsRoute]: + r"""Return a callable for the get tls route method over gRPC. + + Gets details of a single TlsRoute. + + Returns: + Callable[[~.GetTlsRouteRequest], + ~.TlsRoute]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tls_route' not in self._stubs: + self._stubs['get_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetTlsRoute', + request_serializer=tls_route.GetTlsRouteRequest.serialize, + response_deserializer=tls_route.TlsRoute.deserialize, + ) + return self._stubs['get_tls_route'] + + @property + def create_tls_route(self) -> Callable[ + [gcn_tls_route.CreateTlsRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the create tls route method over gRPC. + + Creates a new TlsRoute in a given project and + location. + + Returns: + Callable[[~.CreateTlsRouteRequest], + ~.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_tls_route' not in self._stubs: + self._stubs['create_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateTlsRoute', + request_serializer=gcn_tls_route.CreateTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tls_route'] + + @property + def update_tls_route(self) -> Callable[ + [gcn_tls_route.UpdateTlsRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the update tls route method over gRPC. + + Updates the parameters of a single TlsRoute. + + Returns: + Callable[[~.UpdateTlsRouteRequest], + ~.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_tls_route' not in self._stubs: + self._stubs['update_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateTlsRoute', + request_serializer=gcn_tls_route.UpdateTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tls_route'] + + @property + def delete_tls_route(self) -> Callable[ + [tls_route.DeleteTlsRouteRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete tls route method over gRPC. + + Deletes a single TlsRoute. + + Returns: + Callable[[~.DeleteTlsRouteRequest], + ~.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_tls_route' not in self._stubs: + self._stubs['delete_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteTlsRoute', + request_serializer=tls_route.DeleteTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tls_route'] + + @property + def list_service_bindings(self) -> Callable[ + [service_binding.ListServiceBindingsRequest], + service_binding.ListServiceBindingsResponse]: + r"""Return a callable for the list service bindings method over gRPC. + + Lists ServiceBinding in a given project and location. + + Returns: + Callable[[~.ListServiceBindingsRequest], + ~.ListServiceBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_bindings' not in self._stubs: + self._stubs['list_service_bindings'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListServiceBindings', + request_serializer=service_binding.ListServiceBindingsRequest.serialize, + response_deserializer=service_binding.ListServiceBindingsResponse.deserialize, + ) + return self._stubs['list_service_bindings'] + + @property + def get_service_binding(self) -> Callable[ + [service_binding.GetServiceBindingRequest], + service_binding.ServiceBinding]: + r"""Return a callable for the get service binding method over gRPC. + + Gets details of a single ServiceBinding. + + Returns: + Callable[[~.GetServiceBindingRequest], + ~.ServiceBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_binding' not in self._stubs: + self._stubs['get_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetServiceBinding', + request_serializer=service_binding.GetServiceBindingRequest.serialize, + response_deserializer=service_binding.ServiceBinding.deserialize, + ) + return self._stubs['get_service_binding'] + + @property + def create_service_binding(self) -> Callable[ + [gcn_service_binding.CreateServiceBindingRequest], + operations_pb2.Operation]: + r"""Return a callable for the create service binding method over gRPC. + + Creates a new ServiceBinding in a given project and + location. + + Returns: + Callable[[~.CreateServiceBindingRequest], + ~.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_service_binding' not in self._stubs: + self._stubs['create_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateServiceBinding', + request_serializer=gcn_service_binding.CreateServiceBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service_binding'] + + @property + def delete_service_binding(self) -> Callable[ + [service_binding.DeleteServiceBindingRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service binding method over gRPC. + + Deletes a single ServiceBinding. + + Returns: + Callable[[~.DeleteServiceBindingRequest], + ~.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_service_binding' not in self._stubs: + self._stubs['delete_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteServiceBinding', + request_serializer=service_binding.DeleteServiceBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service_binding'] + + @property + def list_meshes(self) -> Callable[ + [mesh.ListMeshesRequest], + mesh.ListMeshesResponse]: + r"""Return a callable for the list meshes method over gRPC. + + Lists Meshes in a given project and location. + + Returns: + Callable[[~.ListMeshesRequest], + ~.ListMeshesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_meshes' not in self._stubs: + self._stubs['list_meshes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListMeshes', + request_serializer=mesh.ListMeshesRequest.serialize, + response_deserializer=mesh.ListMeshesResponse.deserialize, + ) + return self._stubs['list_meshes'] + + @property + def get_mesh(self) -> Callable[ + [mesh.GetMeshRequest], + mesh.Mesh]: + r"""Return a callable for the get mesh method over gRPC. + + Gets details of a single Mesh. + + Returns: + Callable[[~.GetMeshRequest], + ~.Mesh]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mesh' not in self._stubs: + self._stubs['get_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetMesh', + request_serializer=mesh.GetMeshRequest.serialize, + response_deserializer=mesh.Mesh.deserialize, + ) + return self._stubs['get_mesh'] + + @property + def create_mesh(self) -> Callable[ + [gcn_mesh.CreateMeshRequest], + operations_pb2.Operation]: + r"""Return a callable for the create mesh method over gRPC. + + Creates a new Mesh in a given project and location. + + Returns: + Callable[[~.CreateMeshRequest], + ~.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_mesh' not in self._stubs: + self._stubs['create_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateMesh', + request_serializer=gcn_mesh.CreateMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_mesh'] + + @property + def update_mesh(self) -> Callable[ + [gcn_mesh.UpdateMeshRequest], + operations_pb2.Operation]: + r"""Return a callable for the update mesh method over gRPC. + + Updates the parameters of a single Mesh. + + Returns: + Callable[[~.UpdateMeshRequest], + ~.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_mesh' not in self._stubs: + self._stubs['update_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateMesh', + request_serializer=gcn_mesh.UpdateMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_mesh'] + + @property + def delete_mesh(self) -> Callable[ + [mesh.DeleteMeshRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete mesh method over gRPC. + + Deletes a single Mesh. + + Returns: + Callable[[~.DeleteMeshRequest], + ~.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_mesh' not in self._stubs: + self._stubs['delete_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteMesh', + request_serializer=mesh.DeleteMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_mesh'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'NetworkServicesGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py new file mode 100644 index 000000000000..f4edc43e75ea --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py @@ -0,0 +1,1687 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import 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 + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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 NetworkServicesTransport, DEFAULT_CLIENT_INFO +from .grpc import NetworkServicesGrpcTransport + + +class NetworkServicesGrpcAsyncIOTransport(NetworkServicesTransport): + """gRPC AsyncIO backend transport for NetworkServices. + + 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 = 'networkservices.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 = 'networkservices.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: 'networkservices.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 = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_endpoint_policies(self) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + Awaitable[endpoint_policy.ListEndpointPoliciesResponse]]: + r"""Return a callable for the list endpoint policies method over gRPC. + + Lists EndpointPolicies in a given project and + location. + + Returns: + Callable[[~.ListEndpointPoliciesRequest], + Awaitable[~.ListEndpointPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint_policies' not in self._stubs: + self._stubs['list_endpoint_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListEndpointPolicies', + request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, + response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, + ) + return self._stubs['list_endpoint_policies'] + + @property + def get_endpoint_policy(self) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + Awaitable[endpoint_policy.EndpointPolicy]]: + r"""Return a callable for the get endpoint policy method over gRPC. + + Gets details of a single EndpointPolicy. + + Returns: + Callable[[~.GetEndpointPolicyRequest], + Awaitable[~.EndpointPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_endpoint_policy' not in self._stubs: + self._stubs['get_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetEndpointPolicy', + request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, + response_deserializer=endpoint_policy.EndpointPolicy.deserialize, + ) + return self._stubs['get_endpoint_policy'] + + @property + def create_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create endpoint policy method over gRPC. + + Creates a new EndpointPolicy in a given project and + location. + + Returns: + Callable[[~.CreateEndpointPolicyRequest], + 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_endpoint_policy' not in self._stubs: + self._stubs['create_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateEndpointPolicy', + request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_endpoint_policy'] + + @property + def update_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update endpoint policy method over gRPC. + + Updates the parameters of a single EndpointPolicy. + + Returns: + Callable[[~.UpdateEndpointPolicyRequest], + 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_endpoint_policy' not in self._stubs: + self._stubs['update_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateEndpointPolicy', + request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_endpoint_policy'] + + @property + def delete_endpoint_policy(self) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete endpoint policy method over gRPC. + + Deletes a single EndpointPolicy. + + Returns: + Callable[[~.DeleteEndpointPolicyRequest], + 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_endpoint_policy' not in self._stubs: + self._stubs['delete_endpoint_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteEndpointPolicy', + request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_endpoint_policy'] + + @property + def list_gateways(self) -> Callable[ + [gateway.ListGatewaysRequest], + Awaitable[gateway.ListGatewaysResponse]]: + r"""Return a callable for the list gateways method over gRPC. + + Lists Gateways in a given project and location. + + Returns: + Callable[[~.ListGatewaysRequest], + Awaitable[~.ListGatewaysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_gateways' not in self._stubs: + self._stubs['list_gateways'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListGateways', + request_serializer=gateway.ListGatewaysRequest.serialize, + response_deserializer=gateway.ListGatewaysResponse.deserialize, + ) + return self._stubs['list_gateways'] + + @property + def get_gateway(self) -> Callable[ + [gateway.GetGatewayRequest], + Awaitable[gateway.Gateway]]: + r"""Return a callable for the get gateway method over gRPC. + + Gets details of a single Gateway. + + Returns: + Callable[[~.GetGatewayRequest], + Awaitable[~.Gateway]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_gateway' not in self._stubs: + self._stubs['get_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetGateway', + request_serializer=gateway.GetGatewayRequest.serialize, + response_deserializer=gateway.Gateway.deserialize, + ) + return self._stubs['get_gateway'] + + @property + def create_gateway(self) -> Callable[ + [gcn_gateway.CreateGatewayRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create gateway method over gRPC. + + Creates a new Gateway in a given project and + location. + + Returns: + Callable[[~.CreateGatewayRequest], + 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_gateway' not in self._stubs: + self._stubs['create_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateGateway', + request_serializer=gcn_gateway.CreateGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_gateway'] + + @property + def update_gateway(self) -> Callable[ + [gcn_gateway.UpdateGatewayRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update gateway method over gRPC. + + Updates the parameters of a single Gateway. + + Returns: + Callable[[~.UpdateGatewayRequest], + 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_gateway' not in self._stubs: + self._stubs['update_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateGateway', + request_serializer=gcn_gateway.UpdateGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_gateway'] + + @property + def delete_gateway(self) -> Callable[ + [gateway.DeleteGatewayRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete gateway method over gRPC. + + Deletes a single Gateway. + + Returns: + Callable[[~.DeleteGatewayRequest], + 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_gateway' not in self._stubs: + self._stubs['delete_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteGateway', + request_serializer=gateway.DeleteGatewayRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_gateway'] + + @property + def list_grpc_routes(self) -> Callable[ + [grpc_route.ListGrpcRoutesRequest], + Awaitable[grpc_route.ListGrpcRoutesResponse]]: + r"""Return a callable for the list grpc routes method over gRPC. + + Lists GrpcRoutes in a given project and location. + + Returns: + Callable[[~.ListGrpcRoutesRequest], + Awaitable[~.ListGrpcRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_grpc_routes' not in self._stubs: + self._stubs['list_grpc_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListGrpcRoutes', + request_serializer=grpc_route.ListGrpcRoutesRequest.serialize, + response_deserializer=grpc_route.ListGrpcRoutesResponse.deserialize, + ) + return self._stubs['list_grpc_routes'] + + @property + def get_grpc_route(self) -> Callable[ + [grpc_route.GetGrpcRouteRequest], + Awaitable[grpc_route.GrpcRoute]]: + r"""Return a callable for the get grpc route method over gRPC. + + Gets details of a single GrpcRoute. + + Returns: + Callable[[~.GetGrpcRouteRequest], + Awaitable[~.GrpcRoute]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_grpc_route' not in self._stubs: + self._stubs['get_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetGrpcRoute', + request_serializer=grpc_route.GetGrpcRouteRequest.serialize, + response_deserializer=grpc_route.GrpcRoute.deserialize, + ) + return self._stubs['get_grpc_route'] + + @property + def create_grpc_route(self) -> Callable[ + [gcn_grpc_route.CreateGrpcRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create grpc route method over gRPC. + + Creates a new GrpcRoute in a given project and + location. + + Returns: + Callable[[~.CreateGrpcRouteRequest], + 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_grpc_route' not in self._stubs: + self._stubs['create_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateGrpcRoute', + request_serializer=gcn_grpc_route.CreateGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_grpc_route'] + + @property + def update_grpc_route(self) -> Callable[ + [gcn_grpc_route.UpdateGrpcRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update grpc route method over gRPC. + + Updates the parameters of a single GrpcRoute. + + Returns: + Callable[[~.UpdateGrpcRouteRequest], + 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_grpc_route' not in self._stubs: + self._stubs['update_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateGrpcRoute', + request_serializer=gcn_grpc_route.UpdateGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_grpc_route'] + + @property + def delete_grpc_route(self) -> Callable[ + [grpc_route.DeleteGrpcRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete grpc route method over gRPC. + + Deletes a single GrpcRoute. + + Returns: + Callable[[~.DeleteGrpcRouteRequest], + 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_grpc_route' not in self._stubs: + self._stubs['delete_grpc_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteGrpcRoute', + request_serializer=grpc_route.DeleteGrpcRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_grpc_route'] + + @property + def list_http_routes(self) -> Callable[ + [http_route.ListHttpRoutesRequest], + Awaitable[http_route.ListHttpRoutesResponse]]: + r"""Return a callable for the list http routes method over gRPC. + + Lists HttpRoute in a given project and location. + + Returns: + Callable[[~.ListHttpRoutesRequest], + Awaitable[~.ListHttpRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_http_routes' not in self._stubs: + self._stubs['list_http_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListHttpRoutes', + request_serializer=http_route.ListHttpRoutesRequest.serialize, + response_deserializer=http_route.ListHttpRoutesResponse.deserialize, + ) + return self._stubs['list_http_routes'] + + @property + def get_http_route(self) -> Callable[ + [http_route.GetHttpRouteRequest], + Awaitable[http_route.HttpRoute]]: + r"""Return a callable for the get http route method over gRPC. + + Gets details of a single HttpRoute. + + Returns: + Callable[[~.GetHttpRouteRequest], + Awaitable[~.HttpRoute]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_http_route' not in self._stubs: + self._stubs['get_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetHttpRoute', + request_serializer=http_route.GetHttpRouteRequest.serialize, + response_deserializer=http_route.HttpRoute.deserialize, + ) + return self._stubs['get_http_route'] + + @property + def create_http_route(self) -> Callable[ + [gcn_http_route.CreateHttpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create http route method over gRPC. + + Creates a new HttpRoute in a given project and + location. + + Returns: + Callable[[~.CreateHttpRouteRequest], + 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_http_route' not in self._stubs: + self._stubs['create_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateHttpRoute', + request_serializer=gcn_http_route.CreateHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_http_route'] + + @property + def update_http_route(self) -> Callable[ + [gcn_http_route.UpdateHttpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update http route method over gRPC. + + Updates the parameters of a single HttpRoute. + + Returns: + Callable[[~.UpdateHttpRouteRequest], + 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_http_route' not in self._stubs: + self._stubs['update_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateHttpRoute', + request_serializer=gcn_http_route.UpdateHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_http_route'] + + @property + def delete_http_route(self) -> Callable[ + [http_route.DeleteHttpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete http route method over gRPC. + + Deletes a single HttpRoute. + + Returns: + Callable[[~.DeleteHttpRouteRequest], + 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_http_route' not in self._stubs: + self._stubs['delete_http_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteHttpRoute', + request_serializer=http_route.DeleteHttpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_http_route'] + + @property + def list_tcp_routes(self) -> Callable[ + [tcp_route.ListTcpRoutesRequest], + Awaitable[tcp_route.ListTcpRoutesResponse]]: + r"""Return a callable for the list tcp routes method over gRPC. + + Lists TcpRoute in a given project and location. + + Returns: + Callable[[~.ListTcpRoutesRequest], + Awaitable[~.ListTcpRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tcp_routes' not in self._stubs: + self._stubs['list_tcp_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListTcpRoutes', + request_serializer=tcp_route.ListTcpRoutesRequest.serialize, + response_deserializer=tcp_route.ListTcpRoutesResponse.deserialize, + ) + return self._stubs['list_tcp_routes'] + + @property + def get_tcp_route(self) -> Callable[ + [tcp_route.GetTcpRouteRequest], + Awaitable[tcp_route.TcpRoute]]: + r"""Return a callable for the get tcp route method over gRPC. + + Gets details of a single TcpRoute. + + Returns: + Callable[[~.GetTcpRouteRequest], + Awaitable[~.TcpRoute]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tcp_route' not in self._stubs: + self._stubs['get_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetTcpRoute', + request_serializer=tcp_route.GetTcpRouteRequest.serialize, + response_deserializer=tcp_route.TcpRoute.deserialize, + ) + return self._stubs['get_tcp_route'] + + @property + def create_tcp_route(self) -> Callable[ + [gcn_tcp_route.CreateTcpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create tcp route method over gRPC. + + Creates a new TcpRoute in a given project and + location. + + Returns: + Callable[[~.CreateTcpRouteRequest], + 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_tcp_route' not in self._stubs: + self._stubs['create_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateTcpRoute', + request_serializer=gcn_tcp_route.CreateTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tcp_route'] + + @property + def update_tcp_route(self) -> Callable[ + [gcn_tcp_route.UpdateTcpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update tcp route method over gRPC. + + Updates the parameters of a single TcpRoute. + + Returns: + Callable[[~.UpdateTcpRouteRequest], + 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_tcp_route' not in self._stubs: + self._stubs['update_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateTcpRoute', + request_serializer=gcn_tcp_route.UpdateTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tcp_route'] + + @property + def delete_tcp_route(self) -> Callable[ + [tcp_route.DeleteTcpRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete tcp route method over gRPC. + + Deletes a single TcpRoute. + + Returns: + Callable[[~.DeleteTcpRouteRequest], + 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_tcp_route' not in self._stubs: + self._stubs['delete_tcp_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteTcpRoute', + request_serializer=tcp_route.DeleteTcpRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tcp_route'] + + @property + def list_tls_routes(self) -> Callable[ + [tls_route.ListTlsRoutesRequest], + Awaitable[tls_route.ListTlsRoutesResponse]]: + r"""Return a callable for the list tls routes method over gRPC. + + Lists TlsRoute in a given project and location. + + Returns: + Callable[[~.ListTlsRoutesRequest], + Awaitable[~.ListTlsRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tls_routes' not in self._stubs: + self._stubs['list_tls_routes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListTlsRoutes', + request_serializer=tls_route.ListTlsRoutesRequest.serialize, + response_deserializer=tls_route.ListTlsRoutesResponse.deserialize, + ) + return self._stubs['list_tls_routes'] + + @property + def get_tls_route(self) -> Callable[ + [tls_route.GetTlsRouteRequest], + Awaitable[tls_route.TlsRoute]]: + r"""Return a callable for the get tls route method over gRPC. + + Gets details of a single TlsRoute. + + Returns: + Callable[[~.GetTlsRouteRequest], + Awaitable[~.TlsRoute]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tls_route' not in self._stubs: + self._stubs['get_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetTlsRoute', + request_serializer=tls_route.GetTlsRouteRequest.serialize, + response_deserializer=tls_route.TlsRoute.deserialize, + ) + return self._stubs['get_tls_route'] + + @property + def create_tls_route(self) -> Callable[ + [gcn_tls_route.CreateTlsRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create tls route method over gRPC. + + Creates a new TlsRoute in a given project and + location. + + Returns: + Callable[[~.CreateTlsRouteRequest], + 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_tls_route' not in self._stubs: + self._stubs['create_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateTlsRoute', + request_serializer=gcn_tls_route.CreateTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tls_route'] + + @property + def update_tls_route(self) -> Callable[ + [gcn_tls_route.UpdateTlsRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update tls route method over gRPC. + + Updates the parameters of a single TlsRoute. + + Returns: + Callable[[~.UpdateTlsRouteRequest], + 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_tls_route' not in self._stubs: + self._stubs['update_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateTlsRoute', + request_serializer=gcn_tls_route.UpdateTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tls_route'] + + @property + def delete_tls_route(self) -> Callable[ + [tls_route.DeleteTlsRouteRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete tls route method over gRPC. + + Deletes a single TlsRoute. + + Returns: + Callable[[~.DeleteTlsRouteRequest], + 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_tls_route' not in self._stubs: + self._stubs['delete_tls_route'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteTlsRoute', + request_serializer=tls_route.DeleteTlsRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tls_route'] + + @property + def list_service_bindings(self) -> Callable[ + [service_binding.ListServiceBindingsRequest], + Awaitable[service_binding.ListServiceBindingsResponse]]: + r"""Return a callable for the list service bindings method over gRPC. + + Lists ServiceBinding in a given project and location. + + Returns: + Callable[[~.ListServiceBindingsRequest], + Awaitable[~.ListServiceBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_bindings' not in self._stubs: + self._stubs['list_service_bindings'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListServiceBindings', + request_serializer=service_binding.ListServiceBindingsRequest.serialize, + response_deserializer=service_binding.ListServiceBindingsResponse.deserialize, + ) + return self._stubs['list_service_bindings'] + + @property + def get_service_binding(self) -> Callable[ + [service_binding.GetServiceBindingRequest], + Awaitable[service_binding.ServiceBinding]]: + r"""Return a callable for the get service binding method over gRPC. + + Gets details of a single ServiceBinding. + + Returns: + Callable[[~.GetServiceBindingRequest], + Awaitable[~.ServiceBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_binding' not in self._stubs: + self._stubs['get_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetServiceBinding', + request_serializer=service_binding.GetServiceBindingRequest.serialize, + response_deserializer=service_binding.ServiceBinding.deserialize, + ) + return self._stubs['get_service_binding'] + + @property + def create_service_binding(self) -> Callable[ + [gcn_service_binding.CreateServiceBindingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create service binding method over gRPC. + + Creates a new ServiceBinding in a given project and + location. + + Returns: + Callable[[~.CreateServiceBindingRequest], + 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_service_binding' not in self._stubs: + self._stubs['create_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateServiceBinding', + request_serializer=gcn_service_binding.CreateServiceBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service_binding'] + + @property + def delete_service_binding(self) -> Callable[ + [service_binding.DeleteServiceBindingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service binding method over gRPC. + + Deletes a single ServiceBinding. + + Returns: + Callable[[~.DeleteServiceBindingRequest], + 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_service_binding' not in self._stubs: + self._stubs['delete_service_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteServiceBinding', + request_serializer=service_binding.DeleteServiceBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service_binding'] + + @property + def list_meshes(self) -> Callable[ + [mesh.ListMeshesRequest], + Awaitable[mesh.ListMeshesResponse]]: + r"""Return a callable for the list meshes method over gRPC. + + Lists Meshes in a given project and location. + + Returns: + Callable[[~.ListMeshesRequest], + Awaitable[~.ListMeshesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_meshes' not in self._stubs: + self._stubs['list_meshes'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/ListMeshes', + request_serializer=mesh.ListMeshesRequest.serialize, + response_deserializer=mesh.ListMeshesResponse.deserialize, + ) + return self._stubs['list_meshes'] + + @property + def get_mesh(self) -> Callable[ + [mesh.GetMeshRequest], + Awaitable[mesh.Mesh]]: + r"""Return a callable for the get mesh method over gRPC. + + Gets details of a single Mesh. + + Returns: + Callable[[~.GetMeshRequest], + Awaitable[~.Mesh]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mesh' not in self._stubs: + self._stubs['get_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/GetMesh', + request_serializer=mesh.GetMeshRequest.serialize, + response_deserializer=mesh.Mesh.deserialize, + ) + return self._stubs['get_mesh'] + + @property + def create_mesh(self) -> Callable[ + [gcn_mesh.CreateMeshRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create mesh method over gRPC. + + Creates a new Mesh in a given project and location. + + Returns: + Callable[[~.CreateMeshRequest], + 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_mesh' not in self._stubs: + self._stubs['create_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/CreateMesh', + request_serializer=gcn_mesh.CreateMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_mesh'] + + @property + def update_mesh(self) -> Callable[ + [gcn_mesh.UpdateMeshRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update mesh method over gRPC. + + Updates the parameters of a single Mesh. + + Returns: + Callable[[~.UpdateMeshRequest], + 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_mesh' not in self._stubs: + self._stubs['update_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/UpdateMesh', + request_serializer=gcn_mesh.UpdateMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_mesh'] + + @property + def delete_mesh(self) -> Callable[ + [mesh.DeleteMeshRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete mesh method over gRPC. + + Deletes a single Mesh. + + Returns: + Callable[[~.DeleteMeshRequest], + 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_mesh' not in self._stubs: + self._stubs['delete_mesh'] = self.grpc_channel.unary_unary( + '/google.cloud.networkservices.v1.NetworkServices/DeleteMesh', + request_serializer=mesh.DeleteMeshRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_mesh'] + + 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_endpoint_policies: gapic_v1.method_async.wrap_method( + self.list_endpoint_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint_policy: gapic_v1.method_async.wrap_method( + self.get_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint_policy: gapic_v1.method_async.wrap_method( + self.create_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint_policy: gapic_v1.method_async.wrap_method( + self.update_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint_policy: gapic_v1.method_async.wrap_method( + self.delete_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_gateways: gapic_v1.method_async.wrap_method( + self.list_gateways, + default_timeout=None, + client_info=client_info, + ), + self.get_gateway: gapic_v1.method_async.wrap_method( + self.get_gateway, + default_timeout=None, + client_info=client_info, + ), + self.create_gateway: gapic_v1.method_async.wrap_method( + self.create_gateway, + default_timeout=None, + client_info=client_info, + ), + self.update_gateway: gapic_v1.method_async.wrap_method( + self.update_gateway, + default_timeout=None, + client_info=client_info, + ), + self.delete_gateway: gapic_v1.method_async.wrap_method( + self.delete_gateway, + default_timeout=None, + client_info=client_info, + ), + self.list_grpc_routes: gapic_v1.method_async.wrap_method( + self.list_grpc_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_grpc_route: gapic_v1.method_async.wrap_method( + self.get_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.create_grpc_route: gapic_v1.method_async.wrap_method( + self.create_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.update_grpc_route: gapic_v1.method_async.wrap_method( + self.update_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_grpc_route: gapic_v1.method_async.wrap_method( + self.delete_grpc_route, + default_timeout=None, + client_info=client_info, + ), + self.list_http_routes: gapic_v1.method_async.wrap_method( + self.list_http_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_http_route: gapic_v1.method_async.wrap_method( + self.get_http_route, + default_timeout=None, + client_info=client_info, + ), + self.create_http_route: gapic_v1.method_async.wrap_method( + self.create_http_route, + default_timeout=None, + client_info=client_info, + ), + self.update_http_route: gapic_v1.method_async.wrap_method( + self.update_http_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_http_route: gapic_v1.method_async.wrap_method( + self.delete_http_route, + default_timeout=None, + client_info=client_info, + ), + self.list_tcp_routes: gapic_v1.method_async.wrap_method( + self.list_tcp_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_tcp_route: gapic_v1.method_async.wrap_method( + self.get_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.create_tcp_route: gapic_v1.method_async.wrap_method( + self.create_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.update_tcp_route: gapic_v1.method_async.wrap_method( + self.update_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_tcp_route: gapic_v1.method_async.wrap_method( + self.delete_tcp_route, + default_timeout=None, + client_info=client_info, + ), + self.list_tls_routes: gapic_v1.method_async.wrap_method( + self.list_tls_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_tls_route: gapic_v1.method_async.wrap_method( + self.get_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.create_tls_route: gapic_v1.method_async.wrap_method( + self.create_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.update_tls_route: gapic_v1.method_async.wrap_method( + self.update_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.delete_tls_route: gapic_v1.method_async.wrap_method( + self.delete_tls_route, + default_timeout=None, + client_info=client_info, + ), + self.list_service_bindings: gapic_v1.method_async.wrap_method( + self.list_service_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_service_binding: gapic_v1.method_async.wrap_method( + self.get_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_service_binding: gapic_v1.method_async.wrap_method( + self.create_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_binding: gapic_v1.method_async.wrap_method( + self.delete_service_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_meshes: gapic_v1.method_async.wrap_method( + self.list_meshes, + default_timeout=None, + client_info=client_info, + ), + self.get_mesh: gapic_v1.method_async.wrap_method( + self.get_mesh, + default_timeout=None, + client_info=client_info, + ), + self.create_mesh: gapic_v1.method_async.wrap_method( + self.create_mesh, + default_timeout=None, + client_info=client_info, + ), + self.update_mesh: gapic_v1.method_async.wrap_method( + self.update_mesh, + default_timeout=None, + client_info=client_info, + ), + self.delete_mesh: gapic_v1.method_async.wrap_method( + self.delete_mesh, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'NetworkServicesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py new file mode 100644 index 000000000000..fd6f01e2dfee --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py @@ -0,0 +1,5574 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +from google.longrunning import operations_pb2 # type: ignore + +from .base import NetworkServicesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class NetworkServicesRestInterceptor: + """Interceptor for NetworkServices. + + 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 NetworkServicesRestTransport. + + .. code-block:: python + class MyCustomNetworkServicesInterceptor(NetworkServicesRestInterceptor): + def pre_create_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_endpoint_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_endpoint_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_gateways(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_gateways(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_grpc_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_grpc_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_http_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_http_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_meshes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_meshes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_service_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_service_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tcp_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tcp_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tls_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tls_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NetworkServicesRestTransport(interceptor=MyCustomNetworkServicesInterceptor()) + client = NetworkServicesClient(transport=transport) + + + """ + def pre_create_endpoint_policy(self, request: gcn_endpoint_policy.CreateEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_endpoint_policy.CreateEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_gateway(self, request: gcn_gateway.CreateGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_gateway.CreateGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_gateway + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_grpc_route(self, request: gcn_grpc_route.CreateGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_grpc_route.CreateGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_http_route(self, request: gcn_http_route.CreateHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_http_route.CreateHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_mesh(self, request: gcn_mesh.CreateMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_mesh.CreateMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_service_binding(self, request: gcn_service_binding.CreateServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_service_binding.CreateServiceBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_service_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_tcp_route(self, request: gcn_tcp_route.CreateTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tcp_route.CreateTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_create_tls_route(self, request: gcn_tls_route.CreateTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tls_route.CreateTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_endpoint_policy(self, request: endpoint_policy.DeleteEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.DeleteEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_gateway(self, request: gateway.DeleteGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.DeleteGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_gateway + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_grpc_route(self, request: grpc_route.DeleteGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.DeleteGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_http_route(self, request: http_route.DeleteHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.DeleteHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_mesh(self, request: mesh.DeleteMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.DeleteMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_service_binding(self, request: service_binding.DeleteServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.DeleteServiceBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_service_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_tcp_route(self, request: tcp_route.DeleteTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.DeleteTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_tls_route(self, request: tls_route.DeleteTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.DeleteTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_endpoint_policy(self, request: endpoint_policy.GetEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.GetEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_endpoint_policy(self, response: endpoint_policy.EndpointPolicy) -> endpoint_policy.EndpointPolicy: + """Post-rpc interceptor for get_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_gateway(self, request: gateway.GetGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.GetGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_gateway(self, response: gateway.Gateway) -> gateway.Gateway: + """Post-rpc interceptor for get_gateway + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_grpc_route(self, request: grpc_route.GetGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.GetGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_grpc_route(self, response: grpc_route.GrpcRoute) -> grpc_route.GrpcRoute: + """Post-rpc interceptor for get_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_http_route(self, request: http_route.GetHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.GetHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_http_route(self, response: http_route.HttpRoute) -> http_route.HttpRoute: + """Post-rpc interceptor for get_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_mesh(self, request: mesh.GetMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.GetMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_mesh(self, response: mesh.Mesh) -> mesh.Mesh: + """Post-rpc interceptor for get_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_service_binding(self, request: service_binding.GetServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.GetServiceBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_service_binding(self, response: service_binding.ServiceBinding) -> service_binding.ServiceBinding: + """Post-rpc interceptor for get_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_tcp_route(self, request: tcp_route.GetTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.GetTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_tcp_route(self, response: tcp_route.TcpRoute) -> tcp_route.TcpRoute: + """Post-rpc interceptor for get_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_tls_route(self, request: tls_route.GetTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.GetTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_tls_route(self, response: tls_route.TlsRoute) -> tls_route.TlsRoute: + """Post-rpc interceptor for get_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_endpoint_policies(self, request: endpoint_policy.ListEndpointPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.ListEndpointPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_endpoint_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_endpoint_policies(self, response: endpoint_policy.ListEndpointPoliciesResponse) -> endpoint_policy.ListEndpointPoliciesResponse: + """Post-rpc interceptor for list_endpoint_policies + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_gateways(self, request: gateway.ListGatewaysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.ListGatewaysRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_gateways + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_gateways(self, response: gateway.ListGatewaysResponse) -> gateway.ListGatewaysResponse: + """Post-rpc interceptor for list_gateways + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_grpc_routes(self, request: grpc_route.ListGrpcRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.ListGrpcRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_grpc_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_grpc_routes(self, response: grpc_route.ListGrpcRoutesResponse) -> grpc_route.ListGrpcRoutesResponse: + """Post-rpc interceptor for list_grpc_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_http_routes(self, request: http_route.ListHttpRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.ListHttpRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_http_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_http_routes(self, response: http_route.ListHttpRoutesResponse) -> http_route.ListHttpRoutesResponse: + """Post-rpc interceptor for list_http_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_meshes(self, request: mesh.ListMeshesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.ListMeshesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_meshes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_meshes(self, response: mesh.ListMeshesResponse) -> mesh.ListMeshesResponse: + """Post-rpc interceptor for list_meshes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_service_bindings(self, request: service_binding.ListServiceBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.ListServiceBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_service_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_service_bindings(self, response: service_binding.ListServiceBindingsResponse) -> service_binding.ListServiceBindingsResponse: + """Post-rpc interceptor for list_service_bindings + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_tcp_routes(self, request: tcp_route.ListTcpRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.ListTcpRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tcp_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_tcp_routes(self, response: tcp_route.ListTcpRoutesResponse) -> tcp_route.ListTcpRoutesResponse: + """Post-rpc interceptor for list_tcp_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_tls_routes(self, request: tls_route.ListTlsRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.ListTlsRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tls_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_tls_routes(self, response: tls_route.ListTlsRoutesResponse) -> tls_route.ListTlsRoutesResponse: + """Post-rpc interceptor for list_tls_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_endpoint_policy(self, request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_endpoint_policy.UpdateEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_gateway(self, request: gcn_gateway.UpdateGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_gateway.UpdateGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_gateway + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_grpc_route(self, request: gcn_grpc_route.UpdateGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_grpc_route.UpdateGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_http_route(self, request: gcn_http_route.UpdateHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_http_route.UpdateHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_mesh(self, request: gcn_mesh.UpdateMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_mesh.UpdateMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_tcp_route(self, request: gcn_tcp_route.UpdateTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tcp_route.UpdateTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + def pre_update_tls_route(self, request: gcn_tls_route.UpdateTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tls_route.UpdateTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NetworkServicesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NetworkServicesRestInterceptor + + +class NetworkServicesRestTransport(NetworkServicesTransport): + """REST backend transport for NetworkServices. + + 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 = 'networkservices.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[NetworkServicesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or NetworkServicesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateEndpointPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "endpointPolicyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_endpoint_policy.CreateEndpointPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.CreateEndpointPolicyRequest): + The request object. Request used with the + CreateEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/endpointPolicies', + 'body': 'endpoint_policy', + }, + ] + request, metadata = self._interceptor.pre_create_endpoint_policy(request, metadata) + pb_request = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_endpoint_policy(resp) + return resp + + class _CreateGateway(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "gatewayId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_gateway.CreateGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create gateway method over HTTP. + + Args: + request (~.gcn_gateway.CreateGatewayRequest): + The request object. Request used by the CreateGateway + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/gateways', + 'body': 'gateway', + }, + ] + request, metadata = self._interceptor.pre_create_gateway(request, metadata) + pb_request = gcn_gateway.CreateGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_gateway(resp) + return resp + + class _CreateGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateGrpcRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "grpcRouteId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_grpc_route.CreateGrpcRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create grpc route method over HTTP. + + Args: + request (~.gcn_grpc_route.CreateGrpcRouteRequest): + The request object. Request used by the CreateGrpcRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/grpcRoutes', + 'body': 'grpc_route', + }, + ] + request, metadata = self._interceptor.pre_create_grpc_route(request, metadata) + pb_request = gcn_grpc_route.CreateGrpcRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_grpc_route(resp) + return resp + + class _CreateHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateHttpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "httpRouteId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_http_route.CreateHttpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create http route method over HTTP. + + Args: + request (~.gcn_http_route.CreateHttpRouteRequest): + The request object. Request used by the HttpRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/httpRoutes', + 'body': 'http_route', + }, + ] + request, metadata = self._interceptor.pre_create_http_route(request, metadata) + pb_request = gcn_http_route.CreateHttpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_http_route(resp) + return resp + + class _CreateMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateMesh") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "meshId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_mesh.CreateMeshRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create mesh method over HTTP. + + Args: + request (~.gcn_mesh.CreateMeshRequest): + The request object. Request used by the CreateMesh + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/meshes', + 'body': 'mesh', + }, + ] + request, metadata = self._interceptor.pre_create_mesh(request, metadata) + pb_request = gcn_mesh.CreateMeshRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mesh(resp) + return resp + + class _CreateServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateServiceBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serviceBindingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_service_binding.CreateServiceBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create service binding method over HTTP. + + Args: + request (~.gcn_service_binding.CreateServiceBindingRequest): + The request object. Request used by the ServiceBinding + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/serviceBindings', + 'body': 'service_binding', + }, + ] + request, metadata = self._interceptor.pre_create_service_binding(request, metadata) + pb_request = gcn_service_binding.CreateServiceBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service_binding(resp) + return resp + + class _CreateTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateTcpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "tcpRouteId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_tcp_route.CreateTcpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create tcp route method over HTTP. + + Args: + request (~.gcn_tcp_route.CreateTcpRouteRequest): + The request object. Request used by the TcpRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/tcpRoutes', + 'body': 'tcp_route', + }, + ] + request, metadata = self._interceptor.pre_create_tcp_route(request, metadata) + pb_request = gcn_tcp_route.CreateTcpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_tcp_route(resp) + return resp + + class _CreateTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateTlsRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "tlsRouteId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_tls_route.CreateTlsRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create tls route method over HTTP. + + Args: + request (~.gcn_tls_route.CreateTlsRouteRequest): + The request object. Request used by the TlsRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/tlsRoutes', + 'body': 'tls_route', + }, + ] + request, metadata = self._interceptor.pre_create_tls_route(request, metadata) + pb_request = gcn_tls_route.CreateTlsRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_tls_route(resp) + return resp + + class _DeleteEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteEndpointPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: endpoint_policy.DeleteEndpointPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.DeleteEndpointPolicyRequest): + The request object. Request used with the + DeleteEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/endpointPolicies/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_endpoint_policy(request, metadata) + pb_request = endpoint_policy.DeleteEndpointPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_endpoint_policy(resp) + return resp + + class _DeleteGateway(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gateway.DeleteGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete gateway method over HTTP. + + Args: + request (~.gateway.DeleteGatewayRequest): + The request object. Request used by the DeleteGateway + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/gateways/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_gateway(request, metadata) + pb_request = gateway.DeleteGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_gateway(resp) + return resp + + class _DeleteGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteGrpcRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: grpc_route.DeleteGrpcRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete grpc route method over HTTP. + + Args: + request (~.grpc_route.DeleteGrpcRouteRequest): + The request object. Request used by the DeleteGrpcRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/grpcRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_grpc_route(request, metadata) + pb_request = grpc_route.DeleteGrpcRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_grpc_route(resp) + return resp + + class _DeleteHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteHttpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: http_route.DeleteHttpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete http route method over HTTP. + + Args: + request (~.http_route.DeleteHttpRouteRequest): + The request object. Request used by the DeleteHttpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/httpRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_http_route(request, metadata) + pb_request = http_route.DeleteHttpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_http_route(resp) + return resp + + class _DeleteMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteMesh") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: mesh.DeleteMeshRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete mesh method over HTTP. + + Args: + request (~.mesh.DeleteMeshRequest): + The request object. Request used by the DeleteMesh + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/meshes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_mesh(request, metadata) + pb_request = mesh.DeleteMeshRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_mesh(resp) + return resp + + class _DeleteServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteServiceBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service_binding.DeleteServiceBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete service binding method over HTTP. + + Args: + request (~.service_binding.DeleteServiceBindingRequest): + The request object. Request used by the + DeleteServiceBinding method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/serviceBindings/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_service_binding(request, metadata) + pb_request = service_binding.DeleteServiceBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service_binding(resp) + return resp + + class _DeleteTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteTcpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tcp_route.DeleteTcpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete tcp route method over HTTP. + + Args: + request (~.tcp_route.DeleteTcpRouteRequest): + The request object. Request used by the DeleteTcpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/tcpRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_tcp_route(request, metadata) + pb_request = tcp_route.DeleteTcpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_tcp_route(resp) + return resp + + class _DeleteTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteTlsRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tls_route.DeleteTlsRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete tls route method over HTTP. + + Args: + request (~.tls_route.DeleteTlsRouteRequest): + The request object. Request used by the DeleteTlsRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/tlsRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_tls_route(request, metadata) + pb_request = tls_route.DeleteTlsRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_tls_route(resp) + return resp + + class _GetEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("GetEndpointPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: endpoint_policy.GetEndpointPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> endpoint_policy.EndpointPolicy: + r"""Call the get endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.GetEndpointPolicyRequest): + The request object. Request used with the + GetEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint_policy.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/endpointPolicies/*}', + }, + ] + request, metadata = self._interceptor.pre_get_endpoint_policy(request, metadata) + pb_request = endpoint_policy.GetEndpointPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = endpoint_policy.EndpointPolicy() + pb_resp = endpoint_policy.EndpointPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_endpoint_policy(resp) + return resp + + class _GetGateway(NetworkServicesRestStub): + def __hash__(self): + return hash("GetGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gateway.GetGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gateway.Gateway: + r"""Call the get gateway method over HTTP. + + Args: + request (~.gateway.GetGatewayRequest): + The request object. Request used by the GetGateway + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gateway.Gateway: + Gateway represents the configuration + for a proxy, typically a load balancer. + It captures the ip:port over which the + services are exposed by the proxy, along + with any policy configurations. Routes + have reference to to Gateways to dictate + how requests should be routed by this + Gateway. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/gateways/*}', + }, + ] + request, metadata = self._interceptor.pre_get_gateway(request, metadata) + pb_request = gateway.GetGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gateway.Gateway() + pb_resp = gateway.Gateway.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_gateway(resp) + return resp + + class _GetGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetGrpcRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: grpc_route.GetGrpcRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> grpc_route.GrpcRoute: + r"""Call the get grpc route method over HTTP. + + Args: + request (~.grpc_route.GetGrpcRouteRequest): + The request object. Request used by the GetGrpcRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.grpc_route.GrpcRoute: + GrpcRoute is the resource defining + how gRPC traffic routed by a Mesh or + Gateway resource is routed. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/grpcRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_grpc_route(request, metadata) + pb_request = grpc_route.GetGrpcRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = grpc_route.GrpcRoute() + pb_resp = grpc_route.GrpcRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_grpc_route(resp) + return resp + + class _GetHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetHttpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: http_route.GetHttpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> http_route.HttpRoute: + r"""Call the get http route method over HTTP. + + Args: + request (~.http_route.GetHttpRouteRequest): + The request object. Request used by the GetHttpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.http_route.HttpRoute: + HttpRoute is the resource defining + how HTTP traffic should be routed by a + Mesh or Gateway resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/httpRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_http_route(request, metadata) + pb_request = http_route.GetHttpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = http_route.HttpRoute() + pb_resp = http_route.HttpRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_http_route(resp) + return resp + + class _GetMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("GetMesh") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: mesh.GetMeshRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mesh.Mesh: + r"""Call the get mesh method over HTTP. + + Args: + request (~.mesh.GetMeshRequest): + The request object. Request used by the GetMesh method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mesh.Mesh: + Mesh represents a logical + configuration grouping for workload to + workload communication within a service + mesh. Routes that point to mesh dictate + how requests are routed within this + logical mesh boundary. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/meshes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_mesh(request, metadata) + pb_request = mesh.GetMeshRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mesh.Mesh() + pb_resp = mesh.Mesh.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mesh(resp) + return resp + + class _GetServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("GetServiceBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service_binding.GetServiceBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_binding.ServiceBinding: + r"""Call the get service binding method over HTTP. + + Args: + request (~.service_binding.GetServiceBindingRequest): + The request object. Request used by the GetServiceBinding + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service_binding.ServiceBinding: + ServiceBinding is the resource that + defines a Service Directory Service to + be used in a BackendService resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/serviceBindings/*}', + }, + ] + request, metadata = self._interceptor.pre_get_service_binding(request, metadata) + pb_request = service_binding.GetServiceBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_binding.ServiceBinding() + pb_resp = service_binding.ServiceBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service_binding(resp) + return resp + + class _GetTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetTcpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tcp_route.GetTcpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tcp_route.TcpRoute: + r"""Call the get tcp route method over HTTP. + + Args: + request (~.tcp_route.GetTcpRouteRequest): + The request object. Request used by the GetTcpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tcp_route.TcpRoute: + TcpRoute is the resource defining how + TCP traffic should be routed by a + Mesh/Gateway resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/tcpRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_tcp_route(request, metadata) + pb_request = tcp_route.GetTcpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tcp_route.TcpRoute() + pb_resp = tcp_route.TcpRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tcp_route(resp) + return resp + + class _GetTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetTlsRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tls_route.GetTlsRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tls_route.TlsRoute: + r"""Call the get tls route method over HTTP. + + Args: + request (~.tls_route.GetTlsRouteRequest): + The request object. Request used by the GetTlsRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tls_route.TlsRoute: + TlsRoute defines how traffic should + be routed based on SNI and other + matching L3 attributes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/tlsRoutes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_tls_route(request, metadata) + pb_request = tls_route.GetTlsRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tls_route.TlsRoute() + pb_resp = tls_route.TlsRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tls_route(resp) + return resp + + class _ListEndpointPolicies(NetworkServicesRestStub): + def __hash__(self): + return hash("ListEndpointPolicies") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: endpoint_policy.ListEndpointPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> endpoint_policy.ListEndpointPoliciesResponse: + r"""Call the list endpoint policies method over HTTP. + + Args: + request (~.endpoint_policy.ListEndpointPoliciesRequest): + The request object. Request used with the + ListEndpointPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint_policy.ListEndpointPoliciesResponse: + Response returned by the + ListEndpointPolicies method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/endpointPolicies', + }, + ] + request, metadata = self._interceptor.pre_list_endpoint_policies(request, metadata) + pb_request = endpoint_policy.ListEndpointPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = endpoint_policy.ListEndpointPoliciesResponse() + pb_resp = endpoint_policy.ListEndpointPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_endpoint_policies(resp) + return resp + + class _ListGateways(NetworkServicesRestStub): + def __hash__(self): + return hash("ListGateways") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gateway.ListGatewaysRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gateway.ListGatewaysResponse: + r"""Call the list gateways method over HTTP. + + Args: + request (~.gateway.ListGatewaysRequest): + The request object. Request used with the ListGateways + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gateway.ListGatewaysResponse: + Response returned by the ListGateways + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/gateways', + }, + ] + request, metadata = self._interceptor.pre_list_gateways(request, metadata) + pb_request = gateway.ListGatewaysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gateway.ListGatewaysResponse() + pb_resp = gateway.ListGatewaysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_gateways(resp) + return resp + + class _ListGrpcRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListGrpcRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: grpc_route.ListGrpcRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> grpc_route.ListGrpcRoutesResponse: + r"""Call the list grpc routes method over HTTP. + + Args: + request (~.grpc_route.ListGrpcRoutesRequest): + The request object. Request used with the ListGrpcRoutes + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.grpc_route.ListGrpcRoutesResponse: + Response returned by the + ListGrpcRoutes method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/grpcRoutes', + }, + ] + request, metadata = self._interceptor.pre_list_grpc_routes(request, metadata) + pb_request = grpc_route.ListGrpcRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = grpc_route.ListGrpcRoutesResponse() + pb_resp = grpc_route.ListGrpcRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_grpc_routes(resp) + return resp + + class _ListHttpRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListHttpRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: http_route.ListHttpRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> http_route.ListHttpRoutesResponse: + r"""Call the list http routes method over HTTP. + + Args: + request (~.http_route.ListHttpRoutesRequest): + The request object. Request used with the ListHttpRoutes + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.http_route.ListHttpRoutesResponse: + Response returned by the + ListHttpRoutes method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/httpRoutes', + }, + ] + request, metadata = self._interceptor.pre_list_http_routes(request, metadata) + pb_request = http_route.ListHttpRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = http_route.ListHttpRoutesResponse() + pb_resp = http_route.ListHttpRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_http_routes(resp) + return resp + + class _ListMeshes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListMeshes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: mesh.ListMeshesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mesh.ListMeshesResponse: + r"""Call the list meshes method over HTTP. + + Args: + request (~.mesh.ListMeshesRequest): + The request object. Request used with the ListMeshes + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mesh.ListMeshesResponse: + Response returned by the ListMeshes + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/meshes', + }, + ] + request, metadata = self._interceptor.pre_list_meshes(request, metadata) + pb_request = mesh.ListMeshesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mesh.ListMeshesResponse() + pb_resp = mesh.ListMeshesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_meshes(resp) + return resp + + class _ListServiceBindings(NetworkServicesRestStub): + def __hash__(self): + return hash("ListServiceBindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service_binding.ListServiceBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_binding.ListServiceBindingsResponse: + r"""Call the list service bindings method over HTTP. + + Args: + request (~.service_binding.ListServiceBindingsRequest): + The request object. Request used with the + ListServiceBindings method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service_binding.ListServiceBindingsResponse: + Response returned by the + ListServiceBindings method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/serviceBindings', + }, + ] + request, metadata = self._interceptor.pre_list_service_bindings(request, metadata) + pb_request = service_binding.ListServiceBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_binding.ListServiceBindingsResponse() + pb_resp = service_binding.ListServiceBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_service_bindings(resp) + return resp + + class _ListTcpRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListTcpRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tcp_route.ListTcpRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tcp_route.ListTcpRoutesResponse: + r"""Call the list tcp routes method over HTTP. + + Args: + request (~.tcp_route.ListTcpRoutesRequest): + The request object. Request used with the ListTcpRoutes + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tcp_route.ListTcpRoutesResponse: + Response returned by the + ListTcpRoutes method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/tcpRoutes', + }, + ] + request, metadata = self._interceptor.pre_list_tcp_routes(request, metadata) + pb_request = tcp_route.ListTcpRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tcp_route.ListTcpRoutesResponse() + pb_resp = tcp_route.ListTcpRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tcp_routes(resp) + return resp + + class _ListTlsRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListTlsRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tls_route.ListTlsRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tls_route.ListTlsRoutesResponse: + r"""Call the list tls routes method over HTTP. + + Args: + request (~.tls_route.ListTlsRoutesRequest): + The request object. Request used with the ListTlsRoutes + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tls_route.ListTlsRoutesResponse: + Response returned by the + ListTlsRoutes method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/tlsRoutes', + }, + ] + request, metadata = self._interceptor.pre_list_tls_routes(request, metadata) + pb_request = tls_route.ListTlsRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tls_route.ListTlsRoutesResponse() + pb_resp = tls_route.ListTlsRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tls_routes(resp) + return resp + + class _UpdateEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateEndpointPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.UpdateEndpointPolicyRequest): + The request object. Request used with the + UpdateEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}', + 'body': 'endpoint_policy', + }, + ] + request, metadata = self._interceptor.pre_update_endpoint_policy(request, metadata) + pb_request = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_endpoint_policy(resp) + return resp + + class _UpdateGateway(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_gateway.UpdateGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update gateway method over HTTP. + + Args: + request (~.gcn_gateway.UpdateGatewayRequest): + The request object. Request used by the UpdateGateway + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{gateway.name=projects/*/locations/*/gateways/*}', + 'body': 'gateway', + }, + ] + request, metadata = self._interceptor.pre_update_gateway(request, metadata) + pb_request = gcn_gateway.UpdateGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_gateway(resp) + return resp + + class _UpdateGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateGrpcRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_grpc_route.UpdateGrpcRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update grpc route method over HTTP. + + Args: + request (~.gcn_grpc_route.UpdateGrpcRouteRequest): + The request object. Request used by the UpdateGrpcRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}', + 'body': 'grpc_route', + }, + ] + request, metadata = self._interceptor.pre_update_grpc_route(request, metadata) + pb_request = gcn_grpc_route.UpdateGrpcRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_grpc_route(resp) + return resp + + class _UpdateHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateHttpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_http_route.UpdateHttpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update http route method over HTTP. + + Args: + request (~.gcn_http_route.UpdateHttpRouteRequest): + The request object. Request used by the UpdateHttpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{http_route.name=projects/*/locations/*/httpRoutes/*}', + 'body': 'http_route', + }, + ] + request, metadata = self._interceptor.pre_update_http_route(request, metadata) + pb_request = gcn_http_route.UpdateHttpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_http_route(resp) + return resp + + class _UpdateMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateMesh") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_mesh.UpdateMeshRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update mesh method over HTTP. + + Args: + request (~.gcn_mesh.UpdateMeshRequest): + The request object. Request used by the UpdateMesh + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{mesh.name=projects/*/locations/*/meshes/*}', + 'body': 'mesh', + }, + ] + request, metadata = self._interceptor.pre_update_mesh(request, metadata) + pb_request = gcn_mesh.UpdateMeshRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mesh(resp) + return resp + + class _UpdateTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateTcpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_tcp_route.UpdateTcpRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update tcp route method over HTTP. + + Args: + request (~.gcn_tcp_route.UpdateTcpRouteRequest): + The request object. Request used by the UpdateTcpRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}', + 'body': 'tcp_route', + }, + ] + request, metadata = self._interceptor.pre_update_tcp_route(request, metadata) + pb_request = gcn_tcp_route.UpdateTcpRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_tcp_route(resp) + return resp + + class _UpdateTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateTlsRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gcn_tls_route.UpdateTlsRouteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update tls route method over HTTP. + + Args: + request (~.gcn_tls_route.UpdateTlsRouteRequest): + The request object. Request used by the UpdateTlsRoute + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{tls_route.name=projects/*/locations/*/tlsRoutes/*}', + 'body': 'tls_route', + }, + ] + request, metadata = self._interceptor.pre_update_tls_route(request, metadata) + pb_request = gcn_tls_route.UpdateTlsRouteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_tls_route(resp) + return resp + + @property + def create_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + 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._CreateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_gateway(self) -> Callable[ + [gcn_gateway.CreateGatewayRequest], + 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._CreateGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_grpc_route(self) -> Callable[ + [gcn_grpc_route.CreateGrpcRouteRequest], + 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._CreateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_http_route(self) -> Callable[ + [gcn_http_route.CreateHttpRouteRequest], + 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._CreateHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mesh(self) -> Callable[ + [gcn_mesh.CreateMeshRequest], + 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._CreateMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_service_binding(self) -> Callable[ + [gcn_service_binding.CreateServiceBindingRequest], + 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._CreateServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tcp_route(self) -> Callable[ + [gcn_tcp_route.CreateTcpRouteRequest], + 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._CreateTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tls_route(self) -> Callable[ + [gcn_tls_route.CreateTlsRouteRequest], + 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._CreateTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_endpoint_policy(self) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + 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._DeleteEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_gateway(self) -> Callable[ + [gateway.DeleteGatewayRequest], + 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._DeleteGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_grpc_route(self) -> Callable[ + [grpc_route.DeleteGrpcRouteRequest], + 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._DeleteGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_http_route(self) -> Callable[ + [http_route.DeleteHttpRouteRequest], + 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._DeleteHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mesh(self) -> Callable[ + [mesh.DeleteMeshRequest], + 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._DeleteMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service_binding(self) -> Callable[ + [service_binding.DeleteServiceBindingRequest], + 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._DeleteServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tcp_route(self) -> Callable[ + [tcp_route.DeleteTcpRouteRequest], + 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._DeleteTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tls_route(self) -> Callable[ + [tls_route.DeleteTlsRouteRequest], + 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._DeleteTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_endpoint_policy(self) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + endpoint_policy.EndpointPolicy]: + # 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._GetEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_gateway(self) -> Callable[ + [gateway.GetGatewayRequest], + gateway.Gateway]: + # 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._GetGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_grpc_route(self) -> Callable[ + [grpc_route.GetGrpcRouteRequest], + grpc_route.GrpcRoute]: + # 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._GetGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_http_route(self) -> Callable[ + [http_route.GetHttpRouteRequest], + http_route.HttpRoute]: + # 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._GetHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mesh(self) -> Callable[ + [mesh.GetMeshRequest], + mesh.Mesh]: + # 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._GetMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service_binding(self) -> Callable[ + [service_binding.GetServiceBindingRequest], + service_binding.ServiceBinding]: + # 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._GetServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tcp_route(self) -> Callable[ + [tcp_route.GetTcpRouteRequest], + tcp_route.TcpRoute]: + # 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._GetTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tls_route(self) -> Callable[ + [tls_route.GetTlsRouteRequest], + tls_route.TlsRoute]: + # 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._GetTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_endpoint_policies(self) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + endpoint_policy.ListEndpointPoliciesResponse]: + # 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._ListEndpointPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_gateways(self) -> Callable[ + [gateway.ListGatewaysRequest], + gateway.ListGatewaysResponse]: + # 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._ListGateways(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_grpc_routes(self) -> Callable[ + [grpc_route.ListGrpcRoutesRequest], + grpc_route.ListGrpcRoutesResponse]: + # 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._ListGrpcRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_http_routes(self) -> Callable[ + [http_route.ListHttpRoutesRequest], + http_route.ListHttpRoutesResponse]: + # 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._ListHttpRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_meshes(self) -> Callable[ + [mesh.ListMeshesRequest], + mesh.ListMeshesResponse]: + # 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._ListMeshes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_service_bindings(self) -> Callable[ + [service_binding.ListServiceBindingsRequest], + service_binding.ListServiceBindingsResponse]: + # 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._ListServiceBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tcp_routes(self) -> Callable[ + [tcp_route.ListTcpRoutesRequest], + tcp_route.ListTcpRoutesResponse]: + # 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._ListTcpRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tls_routes(self) -> Callable[ + [tls_route.ListTlsRoutesRequest], + tls_route.ListTlsRoutesResponse]: + # 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._ListTlsRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_endpoint_policy(self) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + 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._UpdateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_gateway(self) -> Callable[ + [gcn_gateway.UpdateGatewayRequest], + 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._UpdateGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_grpc_route(self) -> Callable[ + [gcn_grpc_route.UpdateGrpcRouteRequest], + 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._UpdateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_http_route(self) -> Callable[ + [gcn_http_route.UpdateHttpRouteRequest], + 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._UpdateHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mesh(self) -> Callable[ + [gcn_mesh.UpdateMeshRequest], + 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._UpdateMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tcp_route(self) -> Callable[ + [gcn_tcp_route.UpdateTcpRouteRequest], + 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._UpdateTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tls_route(self) -> Callable[ + [gcn_tls_route.UpdateTlsRouteRequest], + 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._UpdateTlsRoute(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(NetworkServicesRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(NetworkServicesRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(NetworkServicesRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(NetworkServicesRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(NetworkServicesRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(NetworkServicesRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(NetworkServicesRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(NetworkServicesRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(NetworkServicesRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'NetworkServicesRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py new file mode 100644 index 000000000000..4685b6bd1d61 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + EndpointMatcher, + OperationMetadata, + TrafficPortSelector, +) +from .dep import ( + CreateLbRouteExtensionRequest, + CreateLbTrafficExtensionRequest, + DeleteLbRouteExtensionRequest, + DeleteLbTrafficExtensionRequest, + ExtensionChain, + GetLbRouteExtensionRequest, + GetLbTrafficExtensionRequest, + LbRouteExtension, + LbTrafficExtension, + ListLbRouteExtensionsRequest, + ListLbRouteExtensionsResponse, + ListLbTrafficExtensionsRequest, + ListLbTrafficExtensionsResponse, + UpdateLbRouteExtensionRequest, + UpdateLbTrafficExtensionRequest, + EventType, + LoadBalancingScheme, +) +from .endpoint_policy import ( + CreateEndpointPolicyRequest, + DeleteEndpointPolicyRequest, + EndpointPolicy, + GetEndpointPolicyRequest, + ListEndpointPoliciesRequest, + ListEndpointPoliciesResponse, + UpdateEndpointPolicyRequest, +) +from .gateway import ( + CreateGatewayRequest, + DeleteGatewayRequest, + Gateway, + GetGatewayRequest, + ListGatewaysRequest, + ListGatewaysResponse, + UpdateGatewayRequest, +) +from .grpc_route import ( + CreateGrpcRouteRequest, + DeleteGrpcRouteRequest, + GetGrpcRouteRequest, + GrpcRoute, + ListGrpcRoutesRequest, + ListGrpcRoutesResponse, + UpdateGrpcRouteRequest, +) +from .http_route import ( + CreateHttpRouteRequest, + DeleteHttpRouteRequest, + GetHttpRouteRequest, + HttpRoute, + ListHttpRoutesRequest, + ListHttpRoutesResponse, + UpdateHttpRouteRequest, +) +from .mesh import ( + CreateMeshRequest, + DeleteMeshRequest, + GetMeshRequest, + ListMeshesRequest, + ListMeshesResponse, + Mesh, + UpdateMeshRequest, +) +from .service_binding import ( + CreateServiceBindingRequest, + DeleteServiceBindingRequest, + GetServiceBindingRequest, + ListServiceBindingsRequest, + ListServiceBindingsResponse, + ServiceBinding, +) +from .tcp_route import ( + CreateTcpRouteRequest, + DeleteTcpRouteRequest, + GetTcpRouteRequest, + ListTcpRoutesRequest, + ListTcpRoutesResponse, + TcpRoute, + UpdateTcpRouteRequest, +) +from .tls_route import ( + CreateTlsRouteRequest, + DeleteTlsRouteRequest, + GetTlsRouteRequest, + ListTlsRoutesRequest, + ListTlsRoutesResponse, + TlsRoute, + UpdateTlsRouteRequest, +) + +__all__ = ( + 'EndpointMatcher', + 'OperationMetadata', + 'TrafficPortSelector', + 'CreateLbRouteExtensionRequest', + 'CreateLbTrafficExtensionRequest', + 'DeleteLbRouteExtensionRequest', + 'DeleteLbTrafficExtensionRequest', + 'ExtensionChain', + 'GetLbRouteExtensionRequest', + 'GetLbTrafficExtensionRequest', + 'LbRouteExtension', + 'LbTrafficExtension', + 'ListLbRouteExtensionsRequest', + 'ListLbRouteExtensionsResponse', + 'ListLbTrafficExtensionsRequest', + 'ListLbTrafficExtensionsResponse', + 'UpdateLbRouteExtensionRequest', + 'UpdateLbTrafficExtensionRequest', + 'EventType', + 'LoadBalancingScheme', + 'CreateEndpointPolicyRequest', + 'DeleteEndpointPolicyRequest', + 'EndpointPolicy', + 'GetEndpointPolicyRequest', + 'ListEndpointPoliciesRequest', + 'ListEndpointPoliciesResponse', + 'UpdateEndpointPolicyRequest', + 'CreateGatewayRequest', + 'DeleteGatewayRequest', + 'Gateway', + 'GetGatewayRequest', + 'ListGatewaysRequest', + 'ListGatewaysResponse', + 'UpdateGatewayRequest', + 'CreateGrpcRouteRequest', + 'DeleteGrpcRouteRequest', + 'GetGrpcRouteRequest', + 'GrpcRoute', + 'ListGrpcRoutesRequest', + 'ListGrpcRoutesResponse', + 'UpdateGrpcRouteRequest', + 'CreateHttpRouteRequest', + 'DeleteHttpRouteRequest', + 'GetHttpRouteRequest', + 'HttpRoute', + 'ListHttpRoutesRequest', + 'ListHttpRoutesResponse', + 'UpdateHttpRouteRequest', + 'CreateMeshRequest', + 'DeleteMeshRequest', + 'GetMeshRequest', + 'ListMeshesRequest', + 'ListMeshesResponse', + 'Mesh', + 'UpdateMeshRequest', + 'CreateServiceBindingRequest', + 'DeleteServiceBindingRequest', + 'GetServiceBindingRequest', + 'ListServiceBindingsRequest', + 'ListServiceBindingsResponse', + 'ServiceBinding', + 'CreateTcpRouteRequest', + 'DeleteTcpRouteRequest', + 'GetTcpRouteRequest', + 'ListTcpRoutesRequest', + 'ListTcpRoutesResponse', + 'TcpRoute', + 'UpdateTcpRouteRequest', + 'CreateTlsRouteRequest', + 'DeleteTlsRouteRequest', + 'GetTlsRouteRequest', + 'ListTlsRoutesRequest', + 'ListTlsRoutesResponse', + 'TlsRoute', + 'UpdateTlsRouteRequest', +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py new file mode 100644 index 000000000000..0da5791569fc --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'OperationMetadata', + 'TrafficPortSelector', + 'EndpointMatcher', + }, +) + + +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, + ) + + +class TrafficPortSelector(proto.Message): + r"""Specification of a port-based selector. + + Attributes: + ports (MutableSequence[str]): + Optional. A list of ports. Can be port numbers or port range + (example, [80-90] specifies all ports from 80 to 90, + including 80 and 90) or named ports or \* to specify all + ports. If the list is empty, all ports are selected. + """ + + ports: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class EndpointMatcher(proto.Message): + r"""A definition of a matcher that selects endpoints to which the + policies should be applied. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + metadata_label_matcher (google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher): + The matcher is based on node metadata + presented by xDS clients. + + This field is a member of `oneof`_ ``matcher_type``. + """ + + class MetadataLabelMatcher(proto.Message): + r"""The matcher that is based on node metadata presented by xDS + clients. + + Attributes: + metadata_label_match_criteria (google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria): + Specifies how matching should be done. + + Supported values are: MATCH_ANY: At least one of the Labels + specified in the matcher should match the metadata presented + by xDS client. MATCH_ALL: The metadata presented by the xDS + client should contain all of the labels specified here. + + The selection is determined based on the best match. For + example, suppose there are three EndpointPolicy resources + P1, P2 and P3 and if P1 has a the matcher as MATCH_ANY , P2 has MATCH_ALL , and P3 has MATCH_ALL + . + + If a client with label connects, the config from P1 + will be selected. + + If a client with label connects, the config from + P2 will be selected. + + If a client with label connects, the config + from P3 will be selected. + + If there is more than one best match, (for example, if a + config P4 with selector exists and if a client + with label connects), an error will be thrown. + metadata_labels (MutableSequence[google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabels]): + The list of label value pairs that must match labels in the + provided metadata based on filterMatchCriteria This list can + have at most 64 entries. The list can be empty if the match + criteria is MATCH_ANY, to specify a wildcard match (i.e this + matches any client). + """ + class MetadataLabelMatchCriteria(proto.Enum): + r"""Possible criteria values that define logic of how matching is + made. + + Values: + METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED (0): + Default value. Should not be used. + MATCH_ANY (1): + At least one of the Labels specified in the + matcher should match the metadata presented by + xDS client. + MATCH_ALL (2): + The metadata presented by the xDS client + should contain all of the labels specified here. + """ + METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED = 0 + MATCH_ANY = 1 + MATCH_ALL = 2 + + class MetadataLabels(proto.Message): + r"""Defines a name-pair value for a single label. + + Attributes: + label_name (str): + Required. Label name presented as key in xDS + Node Metadata. + label_value (str): + Required. Label value presented as value + corresponding to the above key, in xDS Node + Metadata. + """ + + label_name: str = proto.Field( + proto.STRING, + number=1, + ) + label_value: str = proto.Field( + proto.STRING, + number=2, + ) + + metadata_label_match_criteria: 'EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria' = proto.Field( + proto.ENUM, + number=1, + enum='EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria', + ) + metadata_labels: MutableSequence['EndpointMatcher.MetadataLabelMatcher.MetadataLabels'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EndpointMatcher.MetadataLabelMatcher.MetadataLabels', + ) + + metadata_label_matcher: MetadataLabelMatcher = proto.Field( + proto.MESSAGE, + number=1, + oneof='matcher_type', + message=MetadataLabelMatcher, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py new file mode 100644 index 000000000000..f505dd913257 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py @@ -0,0 +1,945 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkservices.v1', + manifest={ + 'EventType', + 'LoadBalancingScheme', + 'ExtensionChain', + 'LbTrafficExtension', + 'ListLbTrafficExtensionsRequest', + 'ListLbTrafficExtensionsResponse', + 'GetLbTrafficExtensionRequest', + 'CreateLbTrafficExtensionRequest', + 'UpdateLbTrafficExtensionRequest', + 'DeleteLbTrafficExtensionRequest', + 'LbRouteExtension', + 'ListLbRouteExtensionsRequest', + 'ListLbRouteExtensionsResponse', + 'GetLbRouteExtensionRequest', + 'CreateLbRouteExtensionRequest', + 'UpdateLbRouteExtensionRequest', + 'DeleteLbRouteExtensionRequest', + }, +) + + +class EventType(proto.Enum): + r"""The part of the request or response for which the extension + is called. + + Values: + EVENT_TYPE_UNSPECIFIED (0): + Unspecified value. Do not use. + REQUEST_HEADERS (1): + If included in ``supported_events``, the extension is called + when the HTTP request headers arrive. + REQUEST_BODY (2): + If included in ``supported_events``, the extension is called + when the HTTP request body arrives. + RESPONSE_HEADERS (3): + If included in ``supported_events``, the extension is called + when the HTTP response headers arrive. + RESPONSE_BODY (4): + If included in ``supported_events``, the extension is called + when the HTTP response body arrives. + REQUEST_TRAILERS (5): + If included in ``supported_events``, the extension is called + when the HTTP request trailers arrives. + RESPONSE_TRAILERS (6): + If included in ``supported_events``, the extension is called + when the HTTP response trailers arrives. + """ + EVENT_TYPE_UNSPECIFIED = 0 + REQUEST_HEADERS = 1 + REQUEST_BODY = 2 + RESPONSE_HEADERS = 3 + RESPONSE_BODY = 4 + REQUEST_TRAILERS = 5 + RESPONSE_TRAILERS = 6 + + +class LoadBalancingScheme(proto.Enum): + r"""Load balancing schemes supported by the ``LbTrafficExtension`` + resource and ``LbRouteExtension`` resource. For more information, + refer to `Choosing a load + balancer `__. + + Values: + LOAD_BALANCING_SCHEME_UNSPECIFIED (0): + Default value. Do not use. + INTERNAL_MANAGED (1): + Signifies that this is used for Internal + HTTP(S) Load Balancing. + EXTERNAL_MANAGED (2): + Signifies that this is used for External + Managed HTTP(S) Load Balancing. + """ + LOAD_BALANCING_SCHEME_UNSPECIFIED = 0 + INTERNAL_MANAGED = 1 + EXTERNAL_MANAGED = 2 + + +class ExtensionChain(proto.Message): + r"""A single extension chain wrapper that contains the match + conditions and extensions to execute. + + Attributes: + name (str): + Required. The name for this extension chain. + The name is logged as part of the HTTP request + logs. The name must conform with RFC-1034, is + restricted to lower-cased letters, numbers and + hyphens, and can have a maximum length of 63 + characters. Additionally, the first character + must be a letter and the last a letter or a + number. + match_condition (google.cloud.network_services_v1.types.ExtensionChain.MatchCondition): + Required. Conditions under which this chain + is invoked for a request. + extensions (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain.Extension]): + Required. A set of extensions to execute for the matching + request. At least one extension is required. Up to 3 + extensions can be defined for each extension chain for + ``LbTrafficExtension`` resource. ``LbRouteExtension`` chains + are limited to 1 extension per extension chain. + """ + + class MatchCondition(proto.Message): + r"""Conditions under which this chain is invoked for a request. + + Attributes: + cel_expression (str): + Required. A Common Expression Language (CEL) expression that + is used to match requests for which the extension chain is + executed. + + For more information, see `CEL matcher language + reference `__. + """ + + cel_expression: str = proto.Field( + proto.STRING, + number=1, + ) + + class Extension(proto.Message): + r"""A single extension in the chain to execute for the matching + request. + + Attributes: + name (str): + Required. The name for this extension. + The name is logged as part of the HTTP request + logs. The name must conform with RFC-1034, is + restricted to lower-cased letters, numbers and + hyphens, and can have a maximum length of 63 + characters. Additionally, the first character + must be a letter and the last a letter or a + number. + authority (str): + Optional. The ``:authority`` header in the gRPC request sent + from Envoy to the extension service. Required for Callout + extensions. + service (str): + Required. The reference to the service that runs the + extension. + + Currently only callout extensions are supported here. + + To configure a callout extension, ``service`` must be a + fully-qualified reference to a `backend + service `__ + in the format: + ``https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/backendServices/{backendService}`` + or + ``https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}``. + supported_events (MutableSequence[google.cloud.network_services_v1.types.EventType]): + Optional. A set of events during request or response + processing for which this extension is called. This field is + required for the ``LbTrafficExtension`` resource. It must + not be set for the ``LbRouteExtension`` resource. + timeout (google.protobuf.duration_pb2.Duration): + Optional. Specifies the timeout for each + individual message on the stream. The timeout + must be between 10-1000 milliseconds. Required + for Callout extensions. + fail_open (bool): + Optional. Determines how the proxy behaves if the call to + the extension fails or times out. + + When set to ``TRUE``, request or response processing + continues without error. Any subsequent extensions in the + extension chain are also executed. When set to ``FALSE`` or + the default setting of ``FALSE`` is used, one of the + following happens: + + - If response headers have not been delivered to the + downstream client, a generic 500 error is returned to the + client. The error response can be tailored by configuring + a custom error response in the load balancer. + + - If response headers have been delivered, then the HTTP + stream to the downstream client is reset. + forward_headers (MutableSequence[str]): + Optional. List of the HTTP headers to forward + to the extension (from the client or backend). + If omitted, all headers are sent. Each element + is a string indicating the header name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + authority: str = proto.Field( + proto.STRING, + number=2, + ) + service: str = proto.Field( + proto.STRING, + number=3, + ) + supported_events: MutableSequence['EventType'] = proto.RepeatedField( + proto.ENUM, + number=4, + enum='EventType', + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + fail_open: bool = proto.Field( + proto.BOOL, + number=6, + ) + forward_headers: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + match_condition: MatchCondition = proto.Field( + proto.MESSAGE, + number=2, + message=MatchCondition, + ) + extensions: MutableSequence[Extension] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Extension, + ) + + +class LbTrafficExtension(proto.Message): + r"""``LbTrafficExtension`` is a resource that lets the extension service + modify the headers and payloads of both requests and responses + without impacting the choice of backend services or any other + security policies associated with the backend service. + + Attributes: + name (str): + Required. Identifier. Name of the ``LbTrafficExtension`` + resource in the following format: + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + 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. + description (str): + Optional. A human-readable description of the + resource. + labels (MutableMapping[str, str]): + Optional. Set of labels associated with the + ``LbTrafficExtension`` resource. + + The format must comply with `the requirements for + labels `__ + for Google Cloud resources. + forwarding_rules (MutableSequence[str]): + Required. A list of references to the forwarding rules to + which this service extension is attached to. At least one + forwarding rule is required. There can be only one + ``LBTrafficExtension`` resource per forwarding rule. + extension_chains (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain]): + Required. A set of ordered extension chains + that contain the match conditions and extensions + to execute. Match conditions for each extension + chain are evaluated in sequence for a given + request. The first extension chain that has a + condition that matches the request is executed. + Any subsequent extension chains do not execute. + Limited to 5 extension chains per resource. + load_balancing_scheme (google.cloud.network_services_v1.types.LoadBalancingScheme): + Required. All backend services and forwarding rules + referenced by this extension must share the same load + balancing scheme. Supported values: ``INTERNAL_MANAGED``, + ``EXTERNAL_MANAGED``. For more information, refer to + `Choosing a load + balancer `__. + metadata (google.protobuf.struct_pb2.Struct): + Optional. The metadata provided here is included in the + ``ProcessingRequest.metadata_context.filter_metadata`` map + field. The metadata is available under the key + ``com.google.lb_traffic_extension.``. The + following variables are supported in the metadata: + + ``{forwarding_rule_id}`` - substituted with the forwarding + rule's fully qualified resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + forwarding_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + extension_chains: MutableSequence['ExtensionChain'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ExtensionChain', + ) + load_balancing_scheme: 'LoadBalancingScheme' = proto.Field( + proto.ENUM, + number=8, + enum='LoadBalancingScheme', + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) + + +class ListLbTrafficExtensionsRequest(proto.Message): + r"""Message for requesting list of ``LbTrafficExtension`` resources. + + Attributes: + parent (str): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified in + the following format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Requested page size. The server + might return fewer items than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results that the server returns. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListLbTrafficExtensionsResponse(proto.Message): + r"""Message for response to listing ``LbTrafficExtension`` resources. + + Attributes: + lb_traffic_extensions (MutableSequence[google.cloud.network_services_v1.types.LbTrafficExtension]): + The list of ``LbTrafficExtension`` resources. + next_page_token (str): + A token identifying a page of results that + the server returns. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + lb_traffic_extensions: MutableSequence['LbTrafficExtension'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LbTrafficExtension', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetLbTrafficExtensionRequest(proto.Message): + r"""Message for getting a ``LbTrafficExtension`` resource. + + Attributes: + name (str): + Required. A name of the ``LbTrafficExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLbTrafficExtensionRequest(proto.Message): + r"""Message for creating a ``LbTrafficExtension`` resource. + + Attributes: + parent (str): + Required. The parent resource of the ``LbTrafficExtension`` + resource. Must be in the format + ``projects/{project}/locations/{location}``. + lb_traffic_extension_id (str): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` 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 can + ignore the request if it has already been + completed. The server guarantees 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, ignores 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, + ) + lb_traffic_extension_id: str = proto.Field( + proto.STRING, + number=2, + ) + lb_traffic_extension: 'LbTrafficExtension' = proto.Field( + proto.MESSAGE, + number=3, + message='LbTrafficExtension', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateLbTrafficExtensionRequest(proto.Message): + r"""Message for updating a ``LbTrafficExtension`` resource. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Used to specify the fields to be overwritten in + the ``LbTrafficExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten if it + is in the mask. If the user does not specify a mask, then + all fields are overwritten. + lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource being updated. + 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 can + ignore the request if it has already been + completed. The server guarantees 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, ignores 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, + ) + lb_traffic_extension: 'LbTrafficExtension' = proto.Field( + proto.MESSAGE, + number=2, + message='LbTrafficExtension', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteLbTrafficExtensionRequest(proto.Message): + r"""Message for deleting a ``LbTrafficExtension`` resource. + + Attributes: + name (str): + Required. The name of the ``LbTrafficExtension`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + 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 can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes after 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, ignores 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 LbRouteExtension(proto.Message): + r"""``LbRouteExtension`` is a resource that lets you control where + traffic is routed to for a given request. + + Attributes: + name (str): + Required. Identifier. Name of the ``LbRouteExtension`` + resource in the following format: + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + 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. + description (str): + Optional. A human-readable description of the + resource. + labels (MutableMapping[str, str]): + Optional. Set of labels associated with the + ``LbRouteExtension`` resource. + + The format must comply with `the requirements for + labels `__ + for Google Cloud resources. + forwarding_rules (MutableSequence[str]): + Required. A list of references to the forwarding rules to + which this service extension is attached to. At least one + forwarding rule is required. There can be only one + ``LbRouteExtension`` resource per forwarding rule. + extension_chains (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain]): + Required. A set of ordered extension chains + that contain the match conditions and extensions + to execute. Match conditions for each extension + chain are evaluated in sequence for a given + request. The first extension chain that has a + condition that matches the request is executed. + Any subsequent extension chains do not execute. + Limited to 5 extension chains per resource. + load_balancing_scheme (google.cloud.network_services_v1.types.LoadBalancingScheme): + Required. All backend services and forwarding rules + referenced by this extension must share the same load + balancing scheme. Supported values: ``INTERNAL_MANAGED``, + ``EXTERNAL_MANAGED``. For more information, refer to + `Choosing a load + balancer `__. + metadata (google.protobuf.struct_pb2.Struct): + Optional. The metadata provided here is included as part of + the ``metadata_context`` (of type + ``google.protobuf.Struct``) in the ``ProcessingRequest`` + message sent to the extension server. The metadata is + available under the namespace + ``com.google.lb_route_extension.``. The + following variables are supported in the metadata Struct: + + ``{forwarding_rule_id}`` - substituted with the forwarding + rule's fully qualified resource name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + forwarding_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + extension_chains: MutableSequence['ExtensionChain'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ExtensionChain', + ) + load_balancing_scheme: 'LoadBalancingScheme' = proto.Field( + proto.ENUM, + number=8, + enum='LoadBalancingScheme', + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) + + +class ListLbRouteExtensionsRequest(proto.Message): + r"""Message for requesting list of ``LbRouteExtension`` resources. + + Attributes: + parent (str): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in the + following format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Requested page size. The server + might return fewer items than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results that the server returns. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListLbRouteExtensionsResponse(proto.Message): + r"""Message for response to listing ``LbRouteExtension`` resources. + + Attributes: + lb_route_extensions (MutableSequence[google.cloud.network_services_v1.types.LbRouteExtension]): + The list of ``LbRouteExtension`` resources. + next_page_token (str): + A token identifying a page of results that + the server returns. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + lb_route_extensions: MutableSequence['LbRouteExtension'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LbRouteExtension', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetLbRouteExtensionRequest(proto.Message): + r"""Message for getting a ``LbRouteExtension`` resource. + + Attributes: + name (str): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLbRouteExtensionRequest(proto.Message): + r"""Message for creating a ``LbRouteExtension`` resource. + + Attributes: + parent (str): + Required. The parent resource of the ``LbRouteExtension`` + resource. Must be in the format + ``projects/{project}/locations/{location}``. + lb_route_extension_id (str): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): + Required. ``LbRouteExtension`` 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 can + ignore the request if it has already been + completed. The server guarantees 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, ignores 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, + ) + lb_route_extension_id: str = proto.Field( + proto.STRING, + number=2, + ) + lb_route_extension: 'LbRouteExtension' = proto.Field( + proto.MESSAGE, + number=3, + message='LbRouteExtension', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateLbRouteExtensionRequest(proto.Message): + r"""Message for updating a ``LbRouteExtension`` resource. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Used to specify the fields to be overwritten in + the ``LbRouteExtension`` resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field is overwritten if it is in the + mask. If the user does not specify a mask, then all fields + are overwritten. + lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource being updated. + 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 can + ignore the request if it has already been + completed. The server guarantees 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, ignores 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, + ) + lb_route_extension: 'LbRouteExtension' = proto.Field( + proto.MESSAGE, + number=2, + message='LbRouteExtension', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteLbRouteExtensionRequest(proto.Message): + r"""Message for deleting a ``LbRouteExtension`` resource. + + Attributes: + name (str): + Required. The name of the ``LbRouteExtension`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + 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 can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes after 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, ignores 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py new file mode 100644 index 000000000000..ee5afc6ec6ca --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py @@ -0,0 +1,317 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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_services_v1.types import common +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networkservices.v1', + manifest={ + 'EndpointPolicy', + 'ListEndpointPoliciesRequest', + 'ListEndpointPoliciesResponse', + 'GetEndpointPolicyRequest', + 'CreateEndpointPolicyRequest', + 'UpdateEndpointPolicyRequest', + 'DeleteEndpointPolicyRequest', + }, +) + + +class EndpointPolicy(proto.Message): + r"""EndpointPolicy is a resource that helps apply desired + configuration on the endpoints that match specific criteria. For + example, this resource can be used to apply "authentication + config" an all endpoints that serve on port 8080. + + Attributes: + name (str): + Required. Name of the EndpointPolicy resource. It matches + pattern + ``projects/{project}/locations/global/endpointPolicies/{endpoint_policy}``. + 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 EndpointPolicy resource. + type_ (google.cloud.network_services_v1.types.EndpointPolicy.EndpointPolicyType): + Required. The type of endpoint policy. This + is primarily used to validate the configuration. + authorization_policy (str): + Optional. This field specifies the URL of + AuthorizationPolicy resource that applies + authorization policies to the inbound traffic at + the matched endpoints. Refer to Authorization. + If this field is not specified, authorization is + disabled(no authz checks) for this endpoint. + endpoint_matcher (google.cloud.network_services_v1.types.EndpointMatcher): + Required. A matcher that selects endpoints to + which the policies should be applied. + traffic_port_selector (google.cloud.network_services_v1.types.TrafficPortSelector): + Optional. Port selector for the (matched) + endpoints. If no port selector is provided, the + matched config is applied to all ports. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + server_tls_policy (str): + Optional. A URL referring to ServerTlsPolicy + resource. ServerTlsPolicy is used to determine + the authentication policy to be applied to + terminate the inbound traffic at the identified + backends. If this field is not set, + authentication is disabled(open) for this + endpoint. + client_tls_policy (str): + Optional. A URL referring to a ClientTlsPolicy resource. + ClientTlsPolicy can be set to specify the authentication for + traffic from the proxy to the actual endpoints. More + specifically, it is applied to the outgoing traffic from the + proxy to the endpoint. This is typically used for sidecar + model where the proxy identifies itself as endpoint to the + control plane, with the connection between sidecar and + endpoint requiring authentication. If this field is not set, + authentication is disabled(open). Applicable only when + EndpointPolicyType is SIDECAR_PROXY. + """ + class EndpointPolicyType(proto.Enum): + r"""The type of endpoint policy. + + Values: + ENDPOINT_POLICY_TYPE_UNSPECIFIED (0): + Default value. Must not be used. + SIDECAR_PROXY (1): + Represents a proxy deployed as a sidecar. + GRPC_SERVER (2): + Represents a proxyless gRPC backend. + """ + ENDPOINT_POLICY_TYPE_UNSPECIFIED = 0 + SIDECAR_PROXY = 1 + GRPC_SERVER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + type_: EndpointPolicyType = proto.Field( + proto.ENUM, + number=5, + enum=EndpointPolicyType, + ) + authorization_policy: str = proto.Field( + proto.STRING, + number=7, + ) + endpoint_matcher: common.EndpointMatcher = proto.Field( + proto.MESSAGE, + number=9, + message=common.EndpointMatcher, + ) + traffic_port_selector: common.TrafficPortSelector = proto.Field( + proto.MESSAGE, + number=10, + message=common.TrafficPortSelector, + ) + description: str = proto.Field( + proto.STRING, + number=11, + ) + server_tls_policy: str = proto.Field( + proto.STRING, + number=12, + ) + client_tls_policy: str = proto.Field( + proto.STRING, + number=13, + ) + + +class ListEndpointPoliciesRequest(proto.Message): + r"""Request used with the ListEndpointPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of EndpointPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListEndpointPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListEndpointPolicies`` 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 ListEndpointPoliciesResponse(proto.Message): + r"""Response returned by the ListEndpointPolicies method. + + Attributes: + endpoint_policies (MutableSequence[google.cloud.network_services_v1.types.EndpointPolicy]): + List of EndpointPolicy 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 + + endpoint_policies: MutableSequence['EndpointPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EndpointPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEndpointPolicyRequest(proto.Message): + r"""Request used with the GetEndpointPolicy method. + + Attributes: + name (str): + Required. A name of the EndpointPolicy to get. Must be in + the format + ``projects/*/locations/global/endpointPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEndpointPolicyRequest(proto.Message): + r"""Request used with the CreateEndpointPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the EndpointPolicy. Must be + in the format ``projects/*/locations/global``. + endpoint_policy_id (str): + Required. Short name of the EndpointPolicy + resource to be created. E.g. "CustomECS". + endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): + Required. EndpointPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + endpoint_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + endpoint_policy: 'EndpointPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='EndpointPolicy', + ) + + +class UpdateEndpointPolicyRequest(proto.Message): + r"""Request used with the UpdateEndpointPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the EndpointPolicy 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. + endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): + Required. Updated EndpointPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + endpoint_policy: 'EndpointPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='EndpointPolicy', + ) + + +class DeleteEndpointPolicyRequest(proto.Message): + r"""Request used with the DeleteEndpointPolicy method. + + Attributes: + name (str): + Required. A name of the EndpointPolicy to delete. Must be in + the format + ``projects/*/locations/global/endpointPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py new file mode 100644 index 000000000000..8a9f0fb05e9e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'Gateway', + 'ListGatewaysRequest', + 'ListGatewaysResponse', + 'GetGatewayRequest', + 'CreateGatewayRequest', + 'UpdateGatewayRequest', + 'DeleteGatewayRequest', + }, +) + + +class Gateway(proto.Message): + r"""Gateway represents the configuration for a proxy, typically a + load balancer. It captures the ip:port over which the services + are exposed by the proxy, along with any policy configurations. + Routes have reference to to Gateways to dictate how requests + should be routed by this Gateway. + + Attributes: + name (str): + Required. Name of the Gateway resource. It matches pattern + ``projects/*/locations/*/gateways/``. + self_link (str): + Output only. Server-defined URL of this + 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 Gateway resource. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + type_ (google.cloud.network_services_v1.types.Gateway.Type): + Immutable. The type of the customer managed + gateway. This field is required. If unspecified, + an error is returned. + ports (MutableSequence[int]): + Required. One or more ports that the Gateway + must receive traffic on. The proxy binds to the + ports specified. Gateway listen on 0.0.0.0 on + the ports specified below. + scope (str): + Required. Immutable. Scope determines how + configuration across multiple Gateway instances + are merged. The configuration for multiple + Gateway instances with the same scope will be + merged as presented as a single coniguration to + the proxy/load balancer. + + Max length 64 characters. + Scope should start with a letter and can only + have letters, numbers, hyphens. + server_tls_policy (str): + Optional. A fully-qualified ServerTLSPolicy + URL reference. Specifies how TLS traffic is + terminated. If empty, TLS termination is + disabled. + """ + class Type(proto.Enum): + r"""The type of the customer-managed gateway. Possible values are: + + - OPEN_MESH + - SECURE_WEB_GATEWAY + + Values: + TYPE_UNSPECIFIED (0): + The type of the customer managed gateway is + unspecified. + OPEN_MESH (1): + The type of the customer managed gateway is + TrafficDirector Open Mesh. + SECURE_WEB_GATEWAY (2): + The type of the customer managed gateway is + SecureWebGateway (SWG). + """ + TYPE_UNSPECIFIED = 0 + OPEN_MESH = 1 + SECURE_WEB_GATEWAY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=13, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + type_: Type = proto.Field( + proto.ENUM, + number=6, + enum=Type, + ) + ports: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=11, + ) + scope: str = proto.Field( + proto.STRING, + number=8, + ) + server_tls_policy: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ListGatewaysRequest(proto.Message): + r"""Request used with the ListGateways method. + + Attributes: + parent (str): + Required. The project and location from which the Gateways + should be listed, specified in the format + ``projects/*/locations/*``. + page_size (int): + Maximum number of Gateways to return per + call. + page_token (str): + The value returned by the last ``ListGatewaysResponse`` + Indicates that this is a continuation of a prior + ``ListGateways`` 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 ListGatewaysResponse(proto.Message): + r"""Response returned by the ListGateways method. + + Attributes: + gateways (MutableSequence[google.cloud.network_services_v1.types.Gateway]): + List of Gateway 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 + + gateways: MutableSequence['Gateway'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Gateway', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetGatewayRequest(proto.Message): + r"""Request used by the GetGateway method. + + Attributes: + name (str): + Required. A name of the Gateway to get. Must be in the + format ``projects/*/locations/*/gateways/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateGatewayRequest(proto.Message): + r"""Request used by the CreateGateway method. + + Attributes: + parent (str): + Required. The parent resource of the Gateway. Must be in the + format ``projects/*/locations/*``. + gateway_id (str): + Required. Short name of the Gateway resource + to be created. + gateway (google.cloud.network_services_v1.types.Gateway): + Required. Gateway resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + gateway_id: str = proto.Field( + proto.STRING, + number=2, + ) + gateway: 'Gateway' = proto.Field( + proto.MESSAGE, + number=3, + message='Gateway', + ) + + +class UpdateGatewayRequest(proto.Message): + r"""Request used by the UpdateGateway method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Gateway 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. + gateway (google.cloud.network_services_v1.types.Gateway): + Required. Updated Gateway resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + gateway: 'Gateway' = proto.Field( + proto.MESSAGE, + number=2, + message='Gateway', + ) + + +class DeleteGatewayRequest(proto.Message): + r"""Request used by the DeleteGateway method. + + Attributes: + name (str): + Required. A name of the Gateway to delete. Must be in the + format ``projects/*/locations/*/gateways/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py new file mode 100644 index 000000000000..1c56faba95b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py @@ -0,0 +1,719 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # 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.networkservices.v1', + manifest={ + 'GrpcRoute', + 'ListGrpcRoutesRequest', + 'ListGrpcRoutesResponse', + 'GetGrpcRouteRequest', + 'CreateGrpcRouteRequest', + 'UpdateGrpcRouteRequest', + 'DeleteGrpcRouteRequest', + }, +) + + +class GrpcRoute(proto.Message): + r"""GrpcRoute is the resource defining how gRPC traffic routed by + a Mesh or Gateway resource is routed. + + Attributes: + name (str): + Required. Name of the GrpcRoute resource. It matches pattern + ``projects/*/locations/global/grpcRoutes/`` + self_link (str): + Output only. Server-defined URL of this + 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 GrpcRoute resource. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + hostnames (MutableSequence[str]): + Required. Service hostnames with an optional port for which + this route describes traffic. + + Format: [:] + + Hostname is the fully qualified domain name of a network + host. This matches the RFC 1123 definition of a hostname + with 2 notable exceptions: + + - IPs are not allowed. + - A hostname may be prefixed with a wildcard label + (``*.``). The wildcard label must appear by itself as the + first label. + + Hostname can be "precise" which is a domain name without the + terminating dot of a network host (e.g. ``foo.example.com``) + or "wildcard", which is a domain name prefixed with a single + wildcard label (e.g. ``*.example.com``). + + Note that as per RFC1035 and RFC1123, a label must consist + of lower case alphanumeric characters or '-', and must start + and end with an alphanumeric character. No other punctuation + is allowed. + + The routes associated with a Mesh or Gateway must have + unique hostnames. If you attempt to attach multiple routes + with conflicting hostnames, the configuration will be + rejected. + + For example, while it is acceptable for routes for the + hostnames ``*.foo.bar.com`` and ``*.bar.com`` to be + associated with the same route, it is not possible to + associate two routes both with ``*.bar.com`` or both with + ``bar.com``. + + If a port is specified, then gRPC clients must use the + channel URI with the port to match this rule (i.e. + "xds:///service:123"), otherwise they must supply the URI + without a port (i.e. "xds:///service"). + meshes (MutableSequence[str]): + Optional. Meshes defines a list of meshes this GrpcRoute is + attached to, as one of the routing rules to route the + requests served by the mesh. + + Each mesh reference should match the pattern: + ``projects/*/locations/global/meshes/`` + gateways (MutableSequence[str]): + Optional. Gateways defines a list of gateways this GrpcRoute + is attached to, as one of the routing rules to route the + requests served by the gateway. + + Each gateway reference should match the pattern: + ``projects/*/locations/global/gateways/`` + rules (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.RouteRule]): + Required. A list of detailed rules defining + how to route traffic. + Within a single GrpcRoute, the + GrpcRoute.RouteAction associated with the first + matching GrpcRoute.RouteRule will be executed. + At least one rule must be supplied. + """ + + class MethodMatch(proto.Message): + r"""Specifies a match against a method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.cloud.network_services_v1.types.GrpcRoute.MethodMatch.Type): + Optional. Specifies how to match against the + name. If not specified, a default value of + "EXACT" is used. + grpc_service (str): + Required. Name of the service to match + against. If unspecified, will match all + services. + grpc_method (str): + Required. Name of the method to match + against. If unspecified, will match all methods. + case_sensitive (bool): + Optional. Specifies that matches are case sensitive. The + default value is true. case_sensitive must not be used with + a type of REGULAR_EXPRESSION. + + This field is a member of `oneof`_ ``_case_sensitive``. + """ + class Type(proto.Enum): + r"""The type of the match. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified. + EXACT (1): + Will only match the exact name provided. + REGULAR_EXPRESSION (2): + Will interpret grpc_method and grpc_service as regexes. RE2 + syntax is supported. + """ + TYPE_UNSPECIFIED = 0 + EXACT = 1 + REGULAR_EXPRESSION = 2 + + type_: 'GrpcRoute.MethodMatch.Type' = proto.Field( + proto.ENUM, + number=1, + enum='GrpcRoute.MethodMatch.Type', + ) + grpc_service: str = proto.Field( + proto.STRING, + number=2, + ) + grpc_method: str = proto.Field( + proto.STRING, + number=3, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + class HeaderMatch(proto.Message): + r"""A match against a collection of headers. + + Attributes: + type_ (google.cloud.network_services_v1.types.GrpcRoute.HeaderMatch.Type): + Optional. Specifies how to match against the + value of the header. If not specified, a default + value of EXACT is used. + key (str): + Required. The key of the header. + value (str): + Required. The value of the header. + """ + class Type(proto.Enum): + r"""The type of match. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified. + EXACT (1): + Will only match the exact value provided. + REGULAR_EXPRESSION (2): + Will match paths conforming to the prefix + specified by value. RE2 syntax is supported. + """ + TYPE_UNSPECIFIED = 0 + EXACT = 1 + REGULAR_EXPRESSION = 2 + + type_: 'GrpcRoute.HeaderMatch.Type' = proto.Field( + proto.ENUM, + number=1, + enum='GrpcRoute.HeaderMatch.Type', + ) + key: str = proto.Field( + proto.STRING, + number=2, + ) + value: str = proto.Field( + proto.STRING, + number=3, + ) + + class RouteMatch(proto.Message): + r"""Criteria for matching traffic. A RouteMatch will be + considered to match when all supplied fields match. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + method (google.cloud.network_services_v1.types.GrpcRoute.MethodMatch): + Optional. A gRPC method to match against. If + this field is empty or omitted, will match all + methods. + + This field is a member of `oneof`_ ``_method``. + headers (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.HeaderMatch]): + Optional. Specifies a collection of headers + to match. + """ + + method: 'GrpcRoute.MethodMatch' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='GrpcRoute.MethodMatch', + ) + headers: MutableSequence['GrpcRoute.HeaderMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='GrpcRoute.HeaderMatch', + ) + + class Destination(proto.Message): + r"""The destination to which traffic will be routed. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + service_name (str): + Required. The URL of a destination service to + which to route traffic. Must refer to either a + BackendService or ServiceDirectoryService. + + This field is a member of `oneof`_ ``destination_type``. + weight (int): + Optional. Specifies the proportion of + requests forwarded to the backend referenced by + the serviceName field. This is computed as: + + - weight/Sum(weights in this destination list). + For non-zero values, there may be some epsilon + from the exact proportion defined here + depending on the precision an implementation + supports. + + If only one serviceName is specified and it has + a weight greater than 0, 100% of the traffic is + forwarded to that backend. + + If weights are specified for any one service + name, they need to be specified for all of them. + + If weights are unspecified for all services, + then, traffic is distributed in equal + proportions to all of them. + + This field is a member of `oneof`_ ``_weight``. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + oneof='destination_type', + ) + weight: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + class FaultInjectionPolicy(proto.Message): + r"""The specification for fault injection introduced into traffic + to test the resiliency of clients to destination service + failure. As part of fault injection, when clients send requests + to a destination, delays can be introduced on a percentage of + requests before sending those requests to the destination + service. Similarly requests from clients can be aborted by for a + percentage of requests. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + delay (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy.Delay): + The specification for injecting delay to + client requests. + + This field is a member of `oneof`_ ``_delay``. + abort (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy.Abort): + The specification for aborting to client + requests. + + This field is a member of `oneof`_ ``_abort``. + """ + + class Delay(proto.Message): + r"""Specification of how client requests are delayed as part of + fault injection before being sent to a destination. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_delay (google.protobuf.duration_pb2.Duration): + Specify a fixed delay before forwarding the + request. + + This field is a member of `oneof`_ ``_fixed_delay``. + percentage (int): + The percentage of traffic on which delay will be injected. + + The value must be between [0, 100] + + This field is a member of `oneof`_ ``_percentage``. + """ + + fixed_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=duration_pb2.Duration, + ) + percentage: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + class Abort(proto.Message): + r"""Specification of how client requests are aborted as part of + fault injection before being sent to a destination. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + http_status (int): + The HTTP status code used to abort the + request. + The value must be between 200 and 599 inclusive. + + This field is a member of `oneof`_ ``_http_status``. + percentage (int): + The percentage of traffic which will be aborted. + + The value must be between [0, 100] + + This field is a member of `oneof`_ ``_percentage``. + """ + + http_status: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + percentage: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + delay: 'GrpcRoute.FaultInjectionPolicy.Delay' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='GrpcRoute.FaultInjectionPolicy.Delay', + ) + abort: 'GrpcRoute.FaultInjectionPolicy.Abort' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='GrpcRoute.FaultInjectionPolicy.Abort', + ) + + class RetryPolicy(proto.Message): + r"""The specifications for retries. + + Attributes: + retry_conditions (MutableSequence[str]): + - connect-failure: Router will retry on failures connecting + to Backend Services, for example due to connection + timeouts. + - refused-stream: Router will retry if the backend service + resets the stream with a REFUSED_STREAM error code. This + reset type indicates that it is safe to retry. + - cancelled: Router will retry if the gRPC status code in + the response header is set to cancelled + - deadline-exceeded: Router will retry if the gRPC status + code in the response header is set to deadline-exceeded + - resource-exhausted: Router will retry if the gRPC status + code in the response header is set to resource-exhausted + - unavailable: Router will retry if the gRPC status code in + the response header is set to unavailable + num_retries (int): + Specifies the allowed number of retries. This + number must be > 0. If not specified, default to + 1. + """ + + retry_conditions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + num_retries: int = proto.Field( + proto.UINT32, + number=2, + ) + + class RouteAction(proto.Message): + r"""Specifies how to route matched traffic. + + Attributes: + destinations (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.Destination]): + Optional. The destination services to which + traffic should be forwarded. If multiple + destinations are specified, traffic will be + split between Backend Service(s) according to + the weight field of these destinations. + fault_injection_policy (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy): + Optional. The specification for fault injection introduced + into traffic to test the resiliency of clients to + destination service failure. As part of fault injection, + when clients send requests to a destination, delays can be + introduced on a percentage of requests before sending those + requests to the destination service. Similarly requests from + clients can be aborted by for a percentage of requests. + + timeout and retry_policy will be ignored by clients that are + configured with a fault_injection_policy + timeout (google.protobuf.duration_pb2.Duration): + Optional. Specifies the timeout for selected + route. Timeout is computed from the time the + request has been fully processed (i.e. end of + stream) up until the response has been + completely processed. Timeout includes all + retries. + retry_policy (google.cloud.network_services_v1.types.GrpcRoute.RetryPolicy): + Optional. Specifies the retry policy + associated with this route. + """ + + destinations: MutableSequence['GrpcRoute.Destination'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GrpcRoute.Destination', + ) + fault_injection_policy: 'GrpcRoute.FaultInjectionPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='GrpcRoute.FaultInjectionPolicy', + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + retry_policy: 'GrpcRoute.RetryPolicy' = proto.Field( + proto.MESSAGE, + number=8, + message='GrpcRoute.RetryPolicy', + ) + + class RouteRule(proto.Message): + r"""Describes how to route traffic. + + Attributes: + matches (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.RouteMatch]): + Optional. Matches define conditions used for + matching the rule against incoming gRPC + requests. Each match is independent, i.e. this + rule will be matched if ANY one of the matches + is satisfied. If no matches field is specified, + this rule will unconditionally match traffic. + action (google.cloud.network_services_v1.types.GrpcRoute.RouteAction): + Required. A detailed rule defining how to + route traffic. This field is required. + """ + + matches: MutableSequence['GrpcRoute.RouteMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GrpcRoute.RouteMatch', + ) + action: 'GrpcRoute.RouteAction' = proto.Field( + proto.MESSAGE, + number=2, + message='GrpcRoute.RouteAction', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=12, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + hostnames: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + meshes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + gateways: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + rules: MutableSequence[RouteRule] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=RouteRule, + ) + + +class ListGrpcRoutesRequest(proto.Message): + r"""Request used with the ListGrpcRoutes method. + + Attributes: + parent (str): + Required. The project and location from which the GrpcRoutes + should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of GrpcRoutes to return per + call. + page_token (str): + The value returned by the last ``ListGrpcRoutesResponse`` + Indicates that this is a continuation of a prior + ``ListGrpcRoutes`` 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 ListGrpcRoutesResponse(proto.Message): + r"""Response returned by the ListGrpcRoutes method. + + Attributes: + grpc_routes (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute]): + List of GrpcRoute 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 + + grpc_routes: MutableSequence['GrpcRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GrpcRoute', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetGrpcRouteRequest(proto.Message): + r"""Request used by the GetGrpcRoute method. + + Attributes: + name (str): + Required. A name of the GrpcRoute to get. Must be in the + format ``projects/*/locations/global/grpcRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateGrpcRouteRequest(proto.Message): + r"""Request used by the CreateGrpcRoute method. + + Attributes: + parent (str): + Required. The parent resource of the GrpcRoute. Must be in + the format ``projects/*/locations/global``. + grpc_route_id (str): + Required. Short name of the GrpcRoute + resource to be created. + grpc_route (google.cloud.network_services_v1.types.GrpcRoute): + Required. GrpcRoute resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + grpc_route_id: str = proto.Field( + proto.STRING, + number=2, + ) + grpc_route: 'GrpcRoute' = proto.Field( + proto.MESSAGE, + number=3, + message='GrpcRoute', + ) + + +class UpdateGrpcRouteRequest(proto.Message): + r"""Request used by the UpdateGrpcRoute method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the GrpcRoute 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. + grpc_route (google.cloud.network_services_v1.types.GrpcRoute): + Required. Updated GrpcRoute resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + grpc_route: 'GrpcRoute' = proto.Field( + proto.MESSAGE, + number=2, + message='GrpcRoute', + ) + + +class DeleteGrpcRouteRequest(proto.Message): + r"""Request used by the DeleteGrpcRoute method. + + Attributes: + name (str): + Required. A name of the GrpcRoute to delete. Must be in the + format ``projects/*/locations/global/grpcRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py new file mode 100644 index 000000000000..9a2314925e06 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py @@ -0,0 +1,1125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # 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.networkservices.v1', + manifest={ + 'HttpRoute', + 'ListHttpRoutesRequest', + 'ListHttpRoutesResponse', + 'GetHttpRouteRequest', + 'CreateHttpRouteRequest', + 'UpdateHttpRouteRequest', + 'DeleteHttpRouteRequest', + }, +) + + +class HttpRoute(proto.Message): + r"""HttpRoute is the resource defining how HTTP traffic should be + routed by a Mesh or Gateway resource. + + Attributes: + name (str): + Required. Name of the HttpRoute resource. It matches pattern + ``projects/*/locations/global/httpRoutes/http_route_name>``. + self_link (str): + Output only. Server-defined URL of this + resource + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + 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. + hostnames (MutableSequence[str]): + Required. Hostnames define a set of hosts that should match + against the HTTP host header to select a HttpRoute to + process the request. Hostname is the fully qualified domain + name of a network host, as defined by RFC 1123 with the + exception that: + + - IPs are not allowed. + - A hostname may be prefixed with a wildcard label + (``*.``). The wildcard label must appear by itself as the + first label. + + Hostname can be "precise" which is a domain name without the + terminating dot of a network host (e.g. ``foo.example.com``) + or "wildcard", which is a domain name prefixed with a single + wildcard label (e.g. ``*.example.com``). + + Note that as per RFC1035 and RFC1123, a label must consist + of lower case alphanumeric characters or '-', and must start + and end with an alphanumeric character. No other punctuation + is allowed. + + The routes associated with a Mesh or Gateways must have + unique hostnames. If you attempt to attach multiple routes + with conflicting hostnames, the configuration will be + rejected. + + For example, while it is acceptable for routes for the + hostnames ``*.foo.bar.com`` and ``*.bar.com`` to be + associated with the same Mesh (or Gateways under the same + scope), it is not possible to associate two routes both with + ``*.bar.com`` or both with ``bar.com``. + meshes (MutableSequence[str]): + Optional. Meshes defines a list of meshes this HttpRoute is + attached to, as one of the routing rules to route the + requests served by the mesh. + + Each mesh reference should match the pattern: + ``projects/*/locations/global/meshes/`` + + The attached Mesh should be of a type SIDECAR + gateways (MutableSequence[str]): + Optional. Gateways defines a list of gateways this HttpRoute + is attached to, as one of the routing rules to route the + requests served by the gateway. + + Each gateway reference should match the pattern: + ``projects/*/locations/global/gateways/`` + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the HttpRoute resource. + rules (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.RouteRule]): + Required. Rules that define how traffic is + routed and handled. Rules will be matched + sequentially based on the RouteMatch specified + for the rule. + """ + + class HeaderMatch(proto.Message): + r"""Specifies how to select a route rule based on HTTP request + headers. + + 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: + exact_match (str): + The value of the header should match exactly the content of + exact_match. + + This field is a member of `oneof`_ ``MatchType``. + regex_match (str): + The value of the header must match the regular expression + specified in regex_match. For regular expression grammar, + please see: https://github.com/google/re2/wiki/Syntax + + This field is a member of `oneof`_ ``MatchType``. + prefix_match (str): + The value of the header must start with the contents of + prefix_match. + + This field is a member of `oneof`_ ``MatchType``. + present_match (bool): + A header with header_name must exist. The match takes place + whether or not the header has a value. + + This field is a member of `oneof`_ ``MatchType``. + suffix_match (str): + The value of the header must end with the contents of + suffix_match. + + This field is a member of `oneof`_ ``MatchType``. + range_match (google.cloud.network_services_v1.types.HttpRoute.HeaderMatch.IntegerRange): + If specified, the rule will match if the + request header value is within the range. + + This field is a member of `oneof`_ ``MatchType``. + header (str): + The name of the HTTP header to match against. + invert_match (bool): + If specified, the match result will be + inverted before checking. Default value is set + to false. + """ + + class IntegerRange(proto.Message): + r"""Represents an integer value range. + + Attributes: + start (int): + Start of the range (inclusive) + end (int): + End of the range (exclusive) + """ + + start: int = proto.Field( + proto.INT32, + number=1, + ) + end: int = proto.Field( + proto.INT32, + number=2, + ) + + exact_match: str = proto.Field( + proto.STRING, + number=2, + oneof='MatchType', + ) + regex_match: str = proto.Field( + proto.STRING, + number=3, + oneof='MatchType', + ) + prefix_match: str = proto.Field( + proto.STRING, + number=4, + oneof='MatchType', + ) + present_match: bool = proto.Field( + proto.BOOL, + number=5, + oneof='MatchType', + ) + suffix_match: str = proto.Field( + proto.STRING, + number=6, + oneof='MatchType', + ) + range_match: 'HttpRoute.HeaderMatch.IntegerRange' = proto.Field( + proto.MESSAGE, + number=7, + oneof='MatchType', + message='HttpRoute.HeaderMatch.IntegerRange', + ) + header: str = proto.Field( + proto.STRING, + number=1, + ) + invert_match: bool = proto.Field( + proto.BOOL, + number=8, + ) + + class QueryParameterMatch(proto.Message): + r"""Specifications to match a query parameter in the request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + exact_match (str): + The value of the query parameter must exactly match the + contents of exact_match. + + Only one of exact_match, regex_match, or present_match must + be set. + + This field is a member of `oneof`_ ``MatchType``. + regex_match (str): + The value of the query parameter must match the regular + expression specified by regex_match. For regular expression + grammar, please see + https://github.com/google/re2/wiki/Syntax + + Only one of exact_match, regex_match, or present_match must + be set. + + This field is a member of `oneof`_ ``MatchType``. + present_match (bool): + Specifies that the QueryParameterMatcher matches if request + contains query parameter, irrespective of whether the + parameter has a value or not. + + Only one of exact_match, regex_match, or present_match must + be set. + + This field is a member of `oneof`_ ``MatchType``. + query_parameter (str): + The name of the query parameter to match. + """ + + exact_match: str = proto.Field( + proto.STRING, + number=2, + oneof='MatchType', + ) + regex_match: str = proto.Field( + proto.STRING, + number=3, + oneof='MatchType', + ) + present_match: bool = proto.Field( + proto.BOOL, + number=4, + oneof='MatchType', + ) + query_parameter: str = proto.Field( + proto.STRING, + number=1, + ) + + class RouteMatch(proto.Message): + r"""RouteMatch defines specifications used to match requests. If + multiple match types are set, this RouteMatch will match if ALL + type of matches are matched. + + 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: + full_path_match (str): + The HTTP request path value should exactly match this value. + + Only one of full_path_match, prefix_match, or regex_match + should be used. + + This field is a member of `oneof`_ ``PathMatch``. + prefix_match (str): + The HTTP request path value must begin with specified + prefix_match. prefix_match must begin with a /. + + Only one of full_path_match, prefix_match, or regex_match + should be used. + + This field is a member of `oneof`_ ``PathMatch``. + regex_match (str): + The HTTP request path value must satisfy the regular + expression specified by regex_match after removing any query + parameters and anchor supplied with the original URL. For + regular expression grammar, please see + https://github.com/google/re2/wiki/Syntax + + Only one of full_path_match, prefix_match, or regex_match + should be used. + + This field is a member of `oneof`_ ``PathMatch``. + ignore_case (bool): + Specifies if prefix_match and full_path_match matches are + case sensitive. The default value is false. + headers (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.HeaderMatch]): + Specifies a list of HTTP request headers to + match against. ALL of the supplied headers must + be matched. + query_parameters (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.QueryParameterMatch]): + Specifies a list of query parameters to match + against. ALL of the query parameters must be + matched. + """ + + full_path_match: str = proto.Field( + proto.STRING, + number=1, + oneof='PathMatch', + ) + prefix_match: str = proto.Field( + proto.STRING, + number=2, + oneof='PathMatch', + ) + regex_match: str = proto.Field( + proto.STRING, + number=3, + oneof='PathMatch', + ) + ignore_case: bool = proto.Field( + proto.BOOL, + number=4, + ) + headers: MutableSequence['HttpRoute.HeaderMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='HttpRoute.HeaderMatch', + ) + query_parameters: MutableSequence['HttpRoute.QueryParameterMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='HttpRoute.QueryParameterMatch', + ) + + class Destination(proto.Message): + r"""Specifications of a destination to which the request should + be routed to. + + Attributes: + service_name (str): + The URL of a BackendService to route traffic + to. + weight (int): + Specifies the proportion of requests + forwarded to the backend referenced by the + serviceName field. This is computed as: + + - weight/Sum(weights in this destination list). + For non-zero values, there may be some epsilon + from the exact proportion defined here + depending on the precision an implementation + supports. + + If only one serviceName is specified and it has + a weight greater than 0, 100% of the traffic is + forwarded to that backend. + + If weights are specified for any one service + name, they need to be specified for all of them. + + If weights are unspecified for all services, + then, traffic is distributed in equal + proportions to all of them. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + weight: int = proto.Field( + proto.INT32, + number=2, + ) + + class Redirect(proto.Message): + r"""The specification for redirecting traffic. + + Attributes: + host_redirect (str): + The host that will be used in the redirect + response instead of the one that was supplied in + the request. + path_redirect (str): + The path that will be used in the redirect response instead + of the one that was supplied in the request. path_redirect + can not be supplied together with prefix_redirect. Supply + one alone or neither. If neither is supplied, the path of + the original request will be used for the redirect. + prefix_rewrite (str): + Indicates that during redirection, the + matched prefix (or path) should be swapped with + this value. This option allows URLs be + dynamically created based on the request. + response_code (google.cloud.network_services_v1.types.HttpRoute.Redirect.ResponseCode): + The HTTP Status code to use for the redirect. + https_redirect (bool): + If set to true, the URL scheme in the + redirected request is set to https. If set to + false, the URL scheme of the redirected request + will remain the same as that of the request. + + The default is set to false. + strip_query (bool): + if set to true, any accompanying query + portion of the original URL is removed prior to + redirecting the request. If set to false, the + query portion of the original URL is retained. + + The default is set to false. + port_redirect (int): + The port that will be used in the redirected + request instead of the one that was supplied in + the request. + """ + class ResponseCode(proto.Enum): + r"""Supported HTTP response code. + + Values: + RESPONSE_CODE_UNSPECIFIED (0): + Default value + MOVED_PERMANENTLY_DEFAULT (1): + Corresponds to 301. + FOUND (2): + Corresponds to 302. + SEE_OTHER (3): + Corresponds to 303. + TEMPORARY_REDIRECT (4): + Corresponds to 307. In this case, the request + method will be retained. + PERMANENT_REDIRECT (5): + Corresponds to 308. In this case, the request + method will be retained. + """ + RESPONSE_CODE_UNSPECIFIED = 0 + MOVED_PERMANENTLY_DEFAULT = 1 + FOUND = 2 + SEE_OTHER = 3 + TEMPORARY_REDIRECT = 4 + PERMANENT_REDIRECT = 5 + + host_redirect: str = proto.Field( + proto.STRING, + number=1, + ) + path_redirect: str = proto.Field( + proto.STRING, + number=2, + ) + prefix_rewrite: str = proto.Field( + proto.STRING, + number=3, + ) + response_code: 'HttpRoute.Redirect.ResponseCode' = proto.Field( + proto.ENUM, + number=4, + enum='HttpRoute.Redirect.ResponseCode', + ) + https_redirect: bool = proto.Field( + proto.BOOL, + number=5, + ) + strip_query: bool = proto.Field( + proto.BOOL, + number=6, + ) + port_redirect: int = proto.Field( + proto.INT32, + number=7, + ) + + class FaultInjectionPolicy(proto.Message): + r"""The specification for fault injection introduced into traffic + to test the resiliency of clients to destination service + failure. As part of fault injection, when clients send requests + to a destination, delays can be introduced by client proxy on a + percentage of requests before sending those requests to the + destination service. Similarly requests can be aborted by client + proxy for a percentage of requests. + + Attributes: + delay (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy.Delay): + The specification for injecting delay to + client requests. + abort (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy.Abort): + The specification for aborting to client + requests. + """ + + class Delay(proto.Message): + r"""Specification of how client requests are delayed as part of + fault injection before being sent to a destination. + + Attributes: + fixed_delay (google.protobuf.duration_pb2.Duration): + Specify a fixed delay before forwarding the + request. + percentage (int): + The percentage of traffic on which delay will be injected. + + The value must be between [0, 100] + """ + + fixed_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + percentage: int = proto.Field( + proto.INT32, + number=2, + ) + + class Abort(proto.Message): + r"""Specification of how client requests are aborted as part of + fault injection before being sent to a destination. + + Attributes: + http_status (int): + The HTTP status code used to abort the + request. + The value must be between 200 and 599 inclusive. + percentage (int): + The percentage of traffic which will be aborted. + + The value must be between [0, 100] + """ + + http_status: int = proto.Field( + proto.INT32, + number=1, + ) + percentage: int = proto.Field( + proto.INT32, + number=2, + ) + + delay: 'HttpRoute.FaultInjectionPolicy.Delay' = proto.Field( + proto.MESSAGE, + number=1, + message='HttpRoute.FaultInjectionPolicy.Delay', + ) + abort: 'HttpRoute.FaultInjectionPolicy.Abort' = proto.Field( + proto.MESSAGE, + number=2, + message='HttpRoute.FaultInjectionPolicy.Abort', + ) + + class HeaderModifier(proto.Message): + r"""The specification for modifying HTTP header in HTTP request + and HTTP response. + + Attributes: + set (MutableMapping[str, str]): + Completely overwrite/replace the headers with + given map where key is the name of the header, + value is the value of the header. + add (MutableMapping[str, str]): + Add the headers with given map where key is + the name of the header, value is the value of + the header. + remove (MutableSequence[str]): + Remove headers (matching by header names) + specified in the list. + """ + + set: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + add: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + remove: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class URLRewrite(proto.Message): + r"""The specification for modifying the URL of the request, prior + to forwarding the request to the destination. + + Attributes: + path_prefix_rewrite (str): + Prior to forwarding the request to the + selected destination, the matching portion of + the requests path is replaced by this value. + host_rewrite (str): + Prior to forwarding the request to the + selected destination, the requests host header + is replaced by this value. + """ + + path_prefix_rewrite: str = proto.Field( + proto.STRING, + number=1, + ) + host_rewrite: str = proto.Field( + proto.STRING, + number=2, + ) + + class RetryPolicy(proto.Message): + r"""The specifications for retries. + + Attributes: + retry_conditions (MutableSequence[str]): + Specifies one or more conditions when this retry policy + applies. Valid values are: 5xx: Proxy will attempt a retry + if the destination service responds with any 5xx response + code, of if the destination service does not respond at all, + example: disconnect, reset, read timeout, connection failure + and refused streams. + + gateway-error: Similar to 5xx, but only applies to response + codes 502, 503, 504. + + reset: Proxy will attempt a retry if the destination service + does not respond at all (disconnect/reset/read timeout) + + connect-failure: Proxy will retry on failures connecting to + destination for example due to connection timeouts. + + retriable-4xx: Proxy will retry fro retriable 4xx response + codes. Currently the only retriable error supported is 409. + + refused-stream: Proxy will retry if the destination resets + the stream with a REFUSED_STREAM error code. This reset type + indicates that it is safe to retry. + num_retries (int): + Specifies the allowed number of retries. This + number must be > 0. If not specified, default to + 1. + per_try_timeout (google.protobuf.duration_pb2.Duration): + Specifies a non-zero timeout per retry + attempt. + """ + + retry_conditions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + num_retries: int = proto.Field( + proto.INT32, + number=2, + ) + per_try_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + class RequestMirrorPolicy(proto.Message): + r"""Specifies the policy on how requests are shadowed to a + separate mirrored destination service. The proxy does not wait + for responses from the shadow service. Prior to sending traffic + to the shadow service, the host/authority header is suffixed + with -shadow. + + Attributes: + destination (google.cloud.network_services_v1.types.HttpRoute.Destination): + The destination the requests will be mirrored + to. The weight of the destination will be + ignored. + """ + + destination: 'HttpRoute.Destination' = proto.Field( + proto.MESSAGE, + number=1, + message='HttpRoute.Destination', + ) + + class CorsPolicy(proto.Message): + r"""The Specification for allowing client side cross-origin + requests. + + Attributes: + allow_origins (MutableSequence[str]): + Specifies the list of origins that will be allowed to do + CORS requests. An origin is allowed if it matches either an + item in allow_origins or an item in allow_origin_regexes. + allow_origin_regexes (MutableSequence[str]): + Specifies the regular expression patterns + that match allowed origins. For regular + expression grammar, please see + https://github.com/google/re2/wiki/Syntax. + allow_methods (MutableSequence[str]): + Specifies the content for + Access-Control-Allow-Methods header. + allow_headers (MutableSequence[str]): + Specifies the content for + Access-Control-Allow-Headers header. + expose_headers (MutableSequence[str]): + Specifies the content for + Access-Control-Expose-Headers header. + max_age (str): + Specifies how long result of a preflight + request can be cached in seconds. This + translates to the Access-Control-Max-Age header. + allow_credentials (bool): + In response to a preflight request, setting + this to true indicates that the actual request + can include user credentials. This translates to + the Access-Control-Allow-Credentials header. + + Default value is false. + disabled (bool): + If true, the CORS policy is disabled. The + default value is false, which indicates that the + CORS policy is in effect. + """ + + allow_origins: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + allow_origin_regexes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + allow_methods: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + allow_headers: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + expose_headers: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + max_age: str = proto.Field( + proto.STRING, + number=6, + ) + allow_credentials: bool = proto.Field( + proto.BOOL, + number=7, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=8, + ) + + class RouteAction(proto.Message): + r"""The specifications for routing traffic and applying + associated policies. + + Attributes: + destinations (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.Destination]): + The destination to which traffic should be + forwarded. + redirect (google.cloud.network_services_v1.types.HttpRoute.Redirect): + If set, the request is directed as configured + by this field. + fault_injection_policy (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy): + The specification for fault injection introduced into + traffic to test the resiliency of clients to backend service + failure. As part of fault injection, when clients send + requests to a backend service, delays can be introduced on a + percentage of requests before sending those requests to the + backend service. Similarly requests from clients can be + aborted for a percentage of requests. + + timeout and retry_policy will be ignored by clients that are + configured with a fault_injection_policy + request_header_modifier (google.cloud.network_services_v1.types.HttpRoute.HeaderModifier): + The specification for modifying the headers + of a matching request prior to delivery of the + request to the destination. If HeaderModifiers + are set on both the Destination and the + RouteAction, they will be merged. Conflicts + between the two will not be resolved on the + configuration. + response_header_modifier (google.cloud.network_services_v1.types.HttpRoute.HeaderModifier): + The specification for modifying the headers + of a response prior to sending the response back + to the client. If HeaderModifiers are set on + both the Destination and the RouteAction, they + will be merged. Conflicts between the two will + not be resolved on the configuration. + url_rewrite (google.cloud.network_services_v1.types.HttpRoute.URLRewrite): + The specification for rewrite URL before + forwarding requests to the destination. + timeout (google.protobuf.duration_pb2.Duration): + Specifies the timeout for selected route. + Timeout is computed from the time the request + has been fully processed (i.e. end of stream) up + until the response has been completely + processed. Timeout includes all retries. + retry_policy (google.cloud.network_services_v1.types.HttpRoute.RetryPolicy): + Specifies the retry policy associated with + this route. + request_mirror_policy (google.cloud.network_services_v1.types.HttpRoute.RequestMirrorPolicy): + Specifies the policy on how requests intended + for the routes destination are shadowed to a + separate mirrored destination. Proxy will not + wait for the shadow destination to respond + before returning the response. Prior to sending + traffic to the shadow service, the + host/authority header is suffixed with -shadow. + cors_policy (google.cloud.network_services_v1.types.HttpRoute.CorsPolicy): + The specification for allowing client side + cross-origin requests. + """ + + destinations: MutableSequence['HttpRoute.Destination'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='HttpRoute.Destination', + ) + redirect: 'HttpRoute.Redirect' = proto.Field( + proto.MESSAGE, + number=2, + message='HttpRoute.Redirect', + ) + fault_injection_policy: 'HttpRoute.FaultInjectionPolicy' = proto.Field( + proto.MESSAGE, + number=4, + message='HttpRoute.FaultInjectionPolicy', + ) + request_header_modifier: 'HttpRoute.HeaderModifier' = proto.Field( + proto.MESSAGE, + number=5, + message='HttpRoute.HeaderModifier', + ) + response_header_modifier: 'HttpRoute.HeaderModifier' = proto.Field( + proto.MESSAGE, + number=6, + message='HttpRoute.HeaderModifier', + ) + url_rewrite: 'HttpRoute.URLRewrite' = proto.Field( + proto.MESSAGE, + number=7, + message='HttpRoute.URLRewrite', + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + retry_policy: 'HttpRoute.RetryPolicy' = proto.Field( + proto.MESSAGE, + number=9, + message='HttpRoute.RetryPolicy', + ) + request_mirror_policy: 'HttpRoute.RequestMirrorPolicy' = proto.Field( + proto.MESSAGE, + number=10, + message='HttpRoute.RequestMirrorPolicy', + ) + cors_policy: 'HttpRoute.CorsPolicy' = proto.Field( + proto.MESSAGE, + number=11, + message='HttpRoute.CorsPolicy', + ) + + class RouteRule(proto.Message): + r"""Specifies how to match traffic and how to route traffic when + traffic is matched. + + Attributes: + matches (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.RouteMatch]): + A list of matches define conditions used for + matching the rule against incoming HTTP + requests. Each match is independent, i.e. this + rule will be matched if ANY one of the matches + is satisfied. + + If no matches field is specified, this rule will + unconditionally match traffic. + + If a default rule is desired to be configured, + add a rule with no matches specified to the end + of the rules list. + action (google.cloud.network_services_v1.types.HttpRoute.RouteAction): + The detailed rule defining how to route + matched traffic. + """ + + matches: MutableSequence['HttpRoute.RouteMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='HttpRoute.RouteMatch', + ) + action: 'HttpRoute.RouteAction' = proto.Field( + proto.MESSAGE, + number=2, + message='HttpRoute.RouteAction', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=11, + ) + 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, + ) + hostnames: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + meshes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + gateways: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + rules: MutableSequence[RouteRule] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=RouteRule, + ) + + +class ListHttpRoutesRequest(proto.Message): + r"""Request used with the ListHttpRoutes method. + + Attributes: + parent (str): + Required. The project and location from which the HttpRoutes + should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of HttpRoutes to return per + call. + page_token (str): + The value returned by the last ``ListHttpRoutesResponse`` + Indicates that this is a continuation of a prior + ``ListHttpRoutes`` 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 ListHttpRoutesResponse(proto.Message): + r"""Response returned by the ListHttpRoutes method. + + Attributes: + http_routes (MutableSequence[google.cloud.network_services_v1.types.HttpRoute]): + List of HttpRoute 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 + + http_routes: MutableSequence['HttpRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='HttpRoute', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetHttpRouteRequest(proto.Message): + r"""Request used by the GetHttpRoute method. + + Attributes: + name (str): + Required. A name of the HttpRoute to get. Must be in the + format ``projects/*/locations/global/httpRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateHttpRouteRequest(proto.Message): + r"""Request used by the HttpRoute method. + + Attributes: + parent (str): + Required. The parent resource of the HttpRoute. Must be in + the format ``projects/*/locations/global``. + http_route_id (str): + Required. Short name of the HttpRoute + resource to be created. + http_route (google.cloud.network_services_v1.types.HttpRoute): + Required. HttpRoute resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + http_route_id: str = proto.Field( + proto.STRING, + number=2, + ) + http_route: 'HttpRoute' = proto.Field( + proto.MESSAGE, + number=3, + message='HttpRoute', + ) + + +class UpdateHttpRouteRequest(proto.Message): + r"""Request used by the UpdateHttpRoute method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the HttpRoute 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. + http_route (google.cloud.network_services_v1.types.HttpRoute): + Required. Updated HttpRoute resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + http_route: 'HttpRoute' = proto.Field( + proto.MESSAGE, + number=2, + message='HttpRoute', + ) + + +class DeleteHttpRouteRequest(proto.Message): + r"""Request used by the DeleteHttpRoute method. + + Attributes: + name (str): + Required. A name of the HttpRoute to delete. Must be in the + format ``projects/*/locations/global/httpRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py new file mode 100644 index 000000000000..07ef7d0b3809 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'Mesh', + 'ListMeshesRequest', + 'ListMeshesResponse', + 'GetMeshRequest', + 'CreateMeshRequest', + 'UpdateMeshRequest', + 'DeleteMeshRequest', + }, +) + + +class Mesh(proto.Message): + r"""Mesh represents a logical configuration grouping for workload + to workload communication within a service mesh. Routes that + point to mesh dictate how requests are routed within this + logical mesh boundary. + + Attributes: + name (str): + Required. Name of the Mesh resource. It matches pattern + ``projects/*/locations/global/meshes/``. + self_link (str): + Output only. Server-defined URL of this + 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 Mesh resource. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + interception_port (int): + Optional. If set to a valid TCP port + (1-65535), instructs the SIDECAR proxy to listen + on the specified port of localhost (127.0.0.1) + address. The SIDECAR proxy will expect all + traffic to be redirected to this port regardless + of its actual ip:port destination. If unset, a + port '15001' is used as the interception port. + This is applicable only for sidecar proxy + deployments. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=9, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + interception_port: int = proto.Field( + proto.INT32, + number=8, + ) + + +class ListMeshesRequest(proto.Message): + r"""Request used with the ListMeshes method. + + Attributes: + parent (str): + Required. The project and location from which the Meshes + should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of Meshes to return per call. + page_token (str): + The value returned by the last ``ListMeshesResponse`` + Indicates that this is a continuation of a prior + ``ListMeshes`` 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 ListMeshesResponse(proto.Message): + r"""Response returned by the ListMeshes method. + + Attributes: + meshes (MutableSequence[google.cloud.network_services_v1.types.Mesh]): + List of Mesh 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 + + meshes: MutableSequence['Mesh'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Mesh', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMeshRequest(proto.Message): + r"""Request used by the GetMesh method. + + Attributes: + name (str): + Required. A name of the Mesh to get. Must be in the format + ``projects/*/locations/global/meshes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMeshRequest(proto.Message): + r"""Request used by the CreateMesh method. + + Attributes: + parent (str): + Required. The parent resource of the Mesh. Must be in the + format ``projects/*/locations/global``. + mesh_id (str): + Required. Short name of the Mesh resource to + be created. + mesh (google.cloud.network_services_v1.types.Mesh): + Required. Mesh resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mesh_id: str = proto.Field( + proto.STRING, + number=2, + ) + mesh: 'Mesh' = proto.Field( + proto.MESSAGE, + number=3, + message='Mesh', + ) + + +class UpdateMeshRequest(proto.Message): + r"""Request used by the UpdateMesh method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Mesh 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. + mesh (google.cloud.network_services_v1.types.Mesh): + Required. Updated Mesh resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + mesh: 'Mesh' = proto.Field( + proto.MESSAGE, + number=2, + message='Mesh', + ) + + +class DeleteMeshRequest(proto.Message): + r"""Request used by the DeleteMesh method. + + Attributes: + name (str): + Required. A name of the Mesh to delete. Must be in the + format ``projects/*/locations/global/meshes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py new file mode 100644 index 000000000000..3e1267789351 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.networkservices.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py new file mode 100644 index 000000000000..50de16c935d9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'ServiceBinding', + 'ListServiceBindingsRequest', + 'ListServiceBindingsResponse', + 'GetServiceBindingRequest', + 'CreateServiceBindingRequest', + 'DeleteServiceBindingRequest', + }, +) + + +class ServiceBinding(proto.Message): + r"""ServiceBinding is the resource that defines a Service + Directory Service to be used in a BackendService resource. + + Attributes: + name (str): + Required. Name of the ServiceBinding resource. It matches + pattern + ``projects/*/locations/global/serviceBindings/service_binding_name``. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + 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. + service (str): + Required. The full service directory service name of the + format /projects/*/locations/*/namespaces/*/services/* + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the ServiceBinding resource. + """ + + 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, + ) + service: str = proto.Field( + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class ListServiceBindingsRequest(proto.Message): + r"""Request used with the ListServiceBindings method. + + Attributes: + parent (str): + Required. The project and location from which the + ServiceBindings should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of ServiceBindings to return + per call. + page_token (str): + The value returned by the last + ``ListServiceBindingsResponse`` Indicates that this is a + continuation of a prior ``ListRouters`` 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 ListServiceBindingsResponse(proto.Message): + r"""Response returned by the ListServiceBindings method. + + Attributes: + service_bindings (MutableSequence[google.cloud.network_services_v1.types.ServiceBinding]): + List of ServiceBinding 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 + + service_bindings: MutableSequence['ServiceBinding'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ServiceBinding', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceBindingRequest(proto.Message): + r"""Request used by the GetServiceBinding method. + + Attributes: + name (str): + Required. A name of the ServiceBinding to get. Must be in + the format + ``projects/*/locations/global/serviceBindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceBindingRequest(proto.Message): + r"""Request used by the ServiceBinding method. + + Attributes: + parent (str): + Required. The parent resource of the ServiceBinding. Must be + in the format ``projects/*/locations/global``. + service_binding_id (str): + Required. Short name of the ServiceBinding + resource to be created. + service_binding (google.cloud.network_services_v1.types.ServiceBinding): + Required. ServiceBinding resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + service_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + service_binding: 'ServiceBinding' = proto.Field( + proto.MESSAGE, + number=3, + message='ServiceBinding', + ) + + +class DeleteServiceBindingRequest(proto.Message): + r"""Request used by the DeleteServiceBinding method. + + Attributes: + name (str): + Required. A name of the ServiceBinding to delete. Must be in + the format + ``projects/*/locations/global/serviceBindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py new file mode 100644 index 000000000000..2f8d72475645 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py @@ -0,0 +1,405 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'TcpRoute', + 'ListTcpRoutesRequest', + 'ListTcpRoutesResponse', + 'GetTcpRouteRequest', + 'CreateTcpRouteRequest', + 'UpdateTcpRouteRequest', + 'DeleteTcpRouteRequest', + }, +) + + +class TcpRoute(proto.Message): + r"""TcpRoute is the resource defining how TCP traffic should be + routed by a Mesh/Gateway resource. + + Attributes: + name (str): + Required. Name of the TcpRoute resource. It matches pattern + ``projects/*/locations/global/tcpRoutes/tcp_route_name>``. + self_link (str): + Output only. Server-defined URL of this + 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. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + rules (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteRule]): + Required. Rules that define how traffic is + routed and handled. At least one RouteRule must + be supplied. If there are multiple rules then + the action taken will be the first rule to + match. + meshes (MutableSequence[str]): + Optional. Meshes defines a list of meshes this TcpRoute is + attached to, as one of the routing rules to route the + requests served by the mesh. + + Each mesh reference should match the pattern: + ``projects/*/locations/global/meshes/`` + + The attached Mesh should be of a type SIDECAR + gateways (MutableSequence[str]): + Optional. Gateways defines a list of gateways this TcpRoute + is attached to, as one of the routing rules to route the + requests served by the gateway. + + Each gateway reference should match the pattern: + ``projects/*/locations/global/gateways/`` + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the TcpRoute resource. + """ + + class RouteRule(proto.Message): + r"""Specifies how to match traffic and how to route traffic when + traffic is matched. + + Attributes: + matches (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteMatch]): + Optional. RouteMatch defines the predicate + used to match requests to a given action. + Multiple match types are "OR"ed for evaluation. + If no routeMatch field is specified, this rule + will unconditionally match traffic. + action (google.cloud.network_services_v1.types.TcpRoute.RouteAction): + Required. The detailed rule defining how to + route matched traffic. + """ + + matches: MutableSequence['TcpRoute.RouteMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TcpRoute.RouteMatch', + ) + action: 'TcpRoute.RouteAction' = proto.Field( + proto.MESSAGE, + number=2, + message='TcpRoute.RouteAction', + ) + + class RouteMatch(proto.Message): + r"""RouteMatch defines the predicate used to match requests to a + given action. Multiple match types are "OR"ed for evaluation. If + no routeMatch field is specified, this rule will unconditionally + match traffic. + + Attributes: + address (str): + Required. Must be specified in the CIDR range + format. A CIDR range consists of an IP Address + and a prefix length to construct the subnet + mask. By default, the prefix length is 32 (i.e. + matches a single IP address). Only IPV4 + addresses are supported. + Examples: + + "10.0.0.1" - matches against this exact IP + address. "10.0.0.0/8" - matches against any IP + address within the 10.0.0.0 subnet and + 255.255.255.0 mask. + "0.0.0.0/0" - matches against any IP address'. + port (str): + Required. Specifies the destination port to + match against. + """ + + address: str = proto.Field( + proto.STRING, + number=1, + ) + port: str = proto.Field( + proto.STRING, + number=2, + ) + + class RouteAction(proto.Message): + r"""The specifications for routing traffic and applying + associated policies. + + Attributes: + destinations (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteDestination]): + Optional. The destination services to which + traffic should be forwarded. At least one + destination service is required. Only one of + route destination or original destination can be + set. + original_destination (bool): + Optional. If true, Router will use the + destination IP and port of the original + connection as the destination of the request. + Default is false. Only one of route destinations + or original destination can be set. + """ + + destinations: MutableSequence['TcpRoute.RouteDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TcpRoute.RouteDestination', + ) + original_destination: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class RouteDestination(proto.Message): + r"""Describe the destination for traffic to be routed to. + + Attributes: + service_name (str): + Required. The URL of a BackendService to + route traffic to. + weight (int): + Optional. Specifies the proportion of + requests forwarded to the backend referenced by + the serviceName field. This is computed as: + + - weight/Sum(weights in this destination list). + For non-zero values, there may be some epsilon + from the exact proportion defined here + depending on the precision an implementation + supports. + + If only one serviceName is specified and it has + a weight greater than 0, 100% of the traffic is + forwarded to that backend. + + If weights are specified for any one service + name, they need to be specified for all of them. + + If weights are unspecified for all services, + then, traffic is distributed in equal + proportions to all of them. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + weight: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=11, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + rules: MutableSequence[RouteRule] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=RouteRule, + ) + meshes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + gateways: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class ListTcpRoutesRequest(proto.Message): + r"""Request used with the ListTcpRoutes method. + + Attributes: + parent (str): + Required. The project and location from which the TcpRoutes + should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of TcpRoutes to return per + call. + page_token (str): + The value returned by the last ``ListTcpRoutesResponse`` + Indicates that this is a continuation of a prior + ``ListTcpRoutes`` 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 ListTcpRoutesResponse(proto.Message): + r"""Response returned by the ListTcpRoutes method. + + Attributes: + tcp_routes (MutableSequence[google.cloud.network_services_v1.types.TcpRoute]): + List of TcpRoute 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 + + tcp_routes: MutableSequence['TcpRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TcpRoute', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTcpRouteRequest(proto.Message): + r"""Request used by the GetTcpRoute method. + + Attributes: + name (str): + Required. A name of the TcpRoute to get. Must be in the + format ``projects/*/locations/global/tcpRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTcpRouteRequest(proto.Message): + r"""Request used by the TcpRoute method. + + Attributes: + parent (str): + Required. The parent resource of the TcpRoute. Must be in + the format ``projects/*/locations/global``. + tcp_route_id (str): + Required. Short name of the TcpRoute resource + to be created. + tcp_route (google.cloud.network_services_v1.types.TcpRoute): + Required. TcpRoute resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tcp_route_id: str = proto.Field( + proto.STRING, + number=2, + ) + tcp_route: 'TcpRoute' = proto.Field( + proto.MESSAGE, + number=3, + message='TcpRoute', + ) + + +class UpdateTcpRouteRequest(proto.Message): + r"""Request used by the UpdateTcpRoute method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the TcpRoute 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. + tcp_route (google.cloud.network_services_v1.types.TcpRoute): + Required. Updated TcpRoute resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + tcp_route: 'TcpRoute' = proto.Field( + proto.MESSAGE, + number=2, + message='TcpRoute', + ) + + +class DeleteTcpRouteRequest(proto.Message): + r"""Request used by the DeleteTcpRoute method. + + Attributes: + name (str): + Required. A name of the TcpRoute to delete. Must be in the + format ``projects/*/locations/global/tcpRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py new file mode 100644 index 000000000000..dd31245cab16 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py @@ -0,0 +1,366 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.networkservices.v1', + manifest={ + 'TlsRoute', + 'ListTlsRoutesRequest', + 'ListTlsRoutesResponse', + 'GetTlsRouteRequest', + 'CreateTlsRouteRequest', + 'UpdateTlsRouteRequest', + 'DeleteTlsRouteRequest', + }, +) + + +class TlsRoute(proto.Message): + r"""TlsRoute defines how traffic should be routed based on SNI + and other matching L3 attributes. + + Attributes: + name (str): + Required. Name of the TlsRoute resource. It matches pattern + ``projects/*/locations/global/tlsRoutes/tls_route_name>``. + self_link (str): + Output only. Server-defined URL of this + 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. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + rules (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteRule]): + Required. Rules that define how traffic is + routed and handled. At least one RouteRule must + be supplied. If there are multiple rules then + the action taken will be the first rule to + match. + meshes (MutableSequence[str]): + Optional. Meshes defines a list of meshes this TlsRoute is + attached to, as one of the routing rules to route the + requests served by the mesh. + + Each mesh reference should match the pattern: + ``projects/*/locations/global/meshes/`` + + The attached Mesh should be of a type SIDECAR + gateways (MutableSequence[str]): + Optional. Gateways defines a list of gateways this TlsRoute + is attached to, as one of the routing rules to route the + requests served by the gateway. + + Each gateway reference should match the pattern: + ``projects/*/locations/global/gateways/`` + """ + + class RouteRule(proto.Message): + r"""Specifies how to match traffic and how to route traffic when + traffic is matched. + + Attributes: + matches (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteMatch]): + Required. RouteMatch defines the predicate + used to match requests to a given action. + Multiple match types are "OR"ed for evaluation. + action (google.cloud.network_services_v1.types.TlsRoute.RouteAction): + Required. The detailed rule defining how to + route matched traffic. + """ + + matches: MutableSequence['TlsRoute.RouteMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TlsRoute.RouteMatch', + ) + action: 'TlsRoute.RouteAction' = proto.Field( + proto.MESSAGE, + number=2, + message='TlsRoute.RouteAction', + ) + + class RouteMatch(proto.Message): + r"""RouteMatch defines the predicate used to match requests to a + given action. Multiple match types are "AND"ed for evaluation. + If no routeMatch field is specified, this rule will + unconditionally match traffic. + + Attributes: + sni_host (MutableSequence[str]): + Optional. SNI (server name indicator) to match against. SNI + will be matched against all wildcard domains, i.e. + ``www.example.com`` will be first matched against + ``www.example.com``, then ``*.example.com``, then ``*.com.`` + Partial wildcards are not supported, and values like + \*w.example.com are invalid. At least one of sni_host and + alpn is required. Up to 5 sni hosts across all matches can + be set. + alpn (MutableSequence[str]): + Optional. ALPN (Application-Layer Protocol Negotiation) to + match against. Examples: "http/1.1", "h2". At least one of + sni_host and alpn is required. Up to 5 alpns across all + matches can be set. + """ + + sni_host: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + alpn: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class RouteAction(proto.Message): + r"""The specifications for routing traffic and applying + associated policies. + + Attributes: + destinations (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteDestination]): + Required. The destination services to which + traffic should be forwarded. At least one + destination service is required. + """ + + destinations: MutableSequence['TlsRoute.RouteDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TlsRoute.RouteDestination', + ) + + class RouteDestination(proto.Message): + r"""Describe the destination for traffic to be routed to. + + Attributes: + service_name (str): + Required. The URL of a BackendService to + route traffic to. + weight (int): + Optional. Specifies the proportion of requests forwareded to + the backend referenced by the service_name field. This is + computed as: + + - weight/Sum(weights in destinations) Weights in all + destinations does not need to sum up to 100. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + weight: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + self_link: str = proto.Field( + proto.STRING, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + rules: MutableSequence[RouteRule] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=RouteRule, + ) + meshes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + gateways: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class ListTlsRoutesRequest(proto.Message): + r"""Request used with the ListTlsRoutes method. + + Attributes: + parent (str): + Required. The project and location from which the TlsRoutes + should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of TlsRoutes to return per + call. + page_token (str): + The value returned by the last ``ListTlsRoutesResponse`` + Indicates that this is a continuation of a prior + ``ListTlsRoutes`` 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 ListTlsRoutesResponse(proto.Message): + r"""Response returned by the ListTlsRoutes method. + + Attributes: + tls_routes (MutableSequence[google.cloud.network_services_v1.types.TlsRoute]): + List of TlsRoute 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 + + tls_routes: MutableSequence['TlsRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TlsRoute', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTlsRouteRequest(proto.Message): + r"""Request used by the GetTlsRoute method. + + Attributes: + name (str): + Required. A name of the TlsRoute to get. Must be in the + format ``projects/*/locations/global/tlsRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTlsRouteRequest(proto.Message): + r"""Request used by the TlsRoute method. + + Attributes: + parent (str): + Required. The parent resource of the TlsRoute. Must be in + the format ``projects/*/locations/global``. + tls_route_id (str): + Required. Short name of the TlsRoute resource + to be created. + tls_route (google.cloud.network_services_v1.types.TlsRoute): + Required. TlsRoute resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tls_route_id: str = proto.Field( + proto.STRING, + number=2, + ) + tls_route: 'TlsRoute' = proto.Field( + proto.MESSAGE, + number=3, + message='TlsRoute', + ) + + +class UpdateTlsRouteRequest(proto.Message): + r"""Request used by the UpdateTlsRoute method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the TlsRoute 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. + tls_route (google.cloud.network_services_v1.types.TlsRoute): + Required. Updated TlsRoute resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + tls_route: 'TlsRoute' = proto.Field( + proto.MESSAGE, + number=2, + message='TlsRoute', + ) + + +class DeleteTlsRouteRequest(proto.Message): + r"""Request used by the DeleteTlsRoute method. + + Attributes: + name (str): + Required. A name of the TlsRoute to delete. Must be in the + format ``projects/*/locations/global/tlsRoutes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/mypy.ini b/owl-bot-staging/google-cloud-network-services/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-services/v1/noxfile.py b/owl-bot-staging/google-cloud-network-services/v1/noxfile.py new file mode 100644 index 000000000000..ec43a17e9d50 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/noxfile.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-network-services' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/network_services_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + +@nox.session(python=ALL_PYTHON[-1]) +def prerelease_deps(session): + """Run the unit test suite against pre-release versions of dependencies.""" + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # 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 + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/network_services_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py new file mode 100644 index 000000000000..0ac1307872bf --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_CreateLbRouteExtension_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_services_v1 + + +async def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_CreateLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py new file mode 100644 index 000000000000..85540549b0d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_CreateLbRouteExtension_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_services_v1 + + +def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_CreateLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py new file mode 100644 index 000000000000..56f616321d1b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_CreateLbTrafficExtension_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_services_v1 + + +async def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_CreateLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..bd22c3e94a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_CreateLbTrafficExtension_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_services_v1 + + +def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_CreateLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py new file mode 100644 index 000000000000..cd1a9d0a5c69 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_DeleteLbRouteExtension_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_services_v1 + + +async def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_DeleteLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py new file mode 100644 index 000000000000..5e66f1d86d97 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_DeleteLbRouteExtension_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_services_v1 + + +def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_DeleteLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py new file mode 100644 index 000000000000..6e2e6adf3f1b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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_services_v1 + + +async def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_DeleteLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..626f94d2161d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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_services_v1 + + +def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_DeleteLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py new file mode 100644 index 000000000000..028335cb5d78 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_GetLbRouteExtension_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_services_v1 + + +async def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_GetLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py new file mode 100644 index 000000000000..0b2e5dda18bf --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_GetLbRouteExtension_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_services_v1 + + +def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_GetLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py new file mode 100644 index 000000000000..00c42981d8db --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_GetLbTrafficExtension_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_services_v1 + + +async def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_GetLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..80d91ad3565e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_GetLbTrafficExtension_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_services_v1 + + +def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_GetLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py new file mode 100644 index 000000000000..593471a93639 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbRouteExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_ListLbRouteExtensions_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_services_v1 + + +async def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_DepService_ListLbRouteExtensions_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py new file mode 100644 index 000000000000..20871c1d88cc --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbRouteExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_ListLbRouteExtensions_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_services_v1 + + +def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_DepService_ListLbRouteExtensions_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py new file mode 100644 index 000000000000..eae2263dfa61 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbTrafficExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_ListLbTrafficExtensions_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_services_v1 + + +async def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_DepService_ListLbTrafficExtensions_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py new file mode 100644 index 000000000000..47652d7d946d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbTrafficExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_ListLbTrafficExtensions_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_services_v1 + + +def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_DepService_ListLbTrafficExtensions_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py new file mode 100644 index 000000000000..374babed9c1d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_UpdateLbRouteExtension_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_services_v1 + + +async def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_UpdateLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py new file mode 100644 index 000000000000..f75940b38efd --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_UpdateLbRouteExtension_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_services_v1 + + +def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_UpdateLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py new file mode 100644 index 000000000000..315e02bf44d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_UpdateLbTrafficExtension_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_services_v1 + + +async def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_UpdateLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..7857a636ddfb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_DepService_UpdateLbTrafficExtension_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_services_v1 + + +def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_DepService_UpdateLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py new file mode 100644 index 000000000000..4f9088ff8991 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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_services_v1 + + +async def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py new file mode 100644 index 000000000000..6a1f52fb8d9e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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_services_v1 + + +def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py new file mode 100644 index 000000000000..7a22badd7546 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateGateway_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_services_v1 + + +async def sample_create_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.CreateGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + gateway=gateway, + ) + + # Make the request + operation = client.create_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py new file mode 100644 index 000000000000..c07d35724f0b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateGateway_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_services_v1 + + +def sample_create_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.CreateGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + gateway=gateway, + ) + + # Make the request + operation = client.create_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py new file mode 100644 index 000000000000..db209ff10826 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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_services_v1 + + +async def sample_create_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateGrpcRouteRequest( + parent="parent_value", + grpc_route_id="grpc_route_id_value", + grpc_route=grpc_route, + ) + + # Make the request + operation = client.create_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py new file mode 100644 index 000000000000..cb0f154a13d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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_services_v1 + + +def sample_create_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateGrpcRouteRequest( + parent="parent_value", + grpc_route_id="grpc_route_id_value", + grpc_route=grpc_route, + ) + + # Make the request + operation = client.create_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py new file mode 100644 index 000000000000..ff1742598c61 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateHttpRoute_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_services_v1 + + +async def sample_create_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateHttpRouteRequest( + parent="parent_value", + http_route_id="http_route_id_value", + http_route=http_route, + ) + + # Make the request + operation = client.create_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py new file mode 100644 index 000000000000..3d5886a040d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateHttpRoute_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_services_v1 + + +def sample_create_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.CreateHttpRouteRequest( + parent="parent_value", + http_route_id="http_route_id_value", + http_route=http_route, + ) + + # Make the request + operation = client.create_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py new file mode 100644 index 000000000000..cfc92be18af0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateMesh_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_services_v1 + + +async def sample_create_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.CreateMeshRequest( + parent="parent_value", + mesh_id="mesh_id_value", + mesh=mesh, + ) + + # Make the request + operation = client.create_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py new file mode 100644 index 000000000000..f9d0abca3f37 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateMesh_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_services_v1 + + +def sample_create_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.CreateMeshRequest( + parent="parent_value", + mesh_id="mesh_id_value", + mesh=mesh, + ) + + # Make the request + operation = client.create_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py new file mode 100644 index 000000000000..c1fb781d3dbc --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateServiceBinding_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_services_v1 + + +async def sample_create_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + service_binding = network_services_v1.ServiceBinding() + service_binding.name = "name_value" + service_binding.service = "service_value" + + request = network_services_v1.CreateServiceBindingRequest( + parent="parent_value", + service_binding_id="service_binding_id_value", + service_binding=service_binding, + ) + + # Make the request + operation = client.create_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py new file mode 100644 index 000000000000..e29229e5a6c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateServiceBinding_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_services_v1 + + +def sample_create_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + service_binding = network_services_v1.ServiceBinding() + service_binding.name = "name_value" + service_binding.service = "service_value" + + request = network_services_v1.CreateServiceBindingRequest( + parent="parent_value", + service_binding_id="service_binding_id_value", + service_binding=service_binding, + ) + + # Make the request + operation = client.create_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py new file mode 100644 index 000000000000..1ddb222bebab --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateTcpRoute_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_services_v1 + + +async def sample_create_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.CreateTcpRouteRequest( + parent="parent_value", + tcp_route_id="tcp_route_id_value", + tcp_route=tcp_route, + ) + + # Make the request + operation = client.create_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py new file mode 100644 index 000000000000..b87a8f360ae7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateTcpRoute_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_services_v1 + + +def sample_create_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.CreateTcpRouteRequest( + parent="parent_value", + tcp_route_id="tcp_route_id_value", + tcp_route=tcp_route, + ) + + # Make the request + operation = client.create_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py new file mode 100644 index 000000000000..1bdb39d13417 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateTlsRoute_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_services_v1 + + +async def sample_create_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.CreateTlsRouteRequest( + parent="parent_value", + tls_route_id="tls_route_id_value", + tls_route=tls_route, + ) + + # Make the request + operation = client.create_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py new file mode 100644 index 000000000000..ab46802de1da --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_CreateTlsRoute_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_services_v1 + + +def sample_create_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.CreateTlsRouteRequest( + parent="parent_value", + tls_route_id="tls_route_id_value", + tls_route=tls_route, + ) + + # Make the request + operation = client.create_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_CreateTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py new file mode 100644 index 000000000000..ece56b8b6674 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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_services_v1 + + +async def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py new file mode 100644 index 000000000000..0b3da2e0a2b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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_services_v1 + + +def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py new file mode 100644 index 000000000000..2aa82831dcd6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteGateway_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_services_v1 + + +async def sample_delete_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGatewayRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py new file mode 100644 index 000000000000..3a14e483d53d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteGateway_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_services_v1 + + +def sample_delete_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGatewayRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py new file mode 100644 index 000000000000..10669e135a35 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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_services_v1 + + +async def sample_delete_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGrpcRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py new file mode 100644 index 000000000000..def384b2c2e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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_services_v1 + + +def sample_delete_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteGrpcRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py new file mode 100644 index 000000000000..64545a297d68 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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_services_v1 + + +async def sample_delete_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteHttpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py new file mode 100644 index 000000000000..4ddd15a8a2c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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_services_v1 + + +def sample_delete_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteHttpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py new file mode 100644 index 000000000000..7bb1b8e4fb2e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteMesh_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_services_v1 + + +async def sample_delete_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteMeshRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py new file mode 100644 index 000000000000..a1b14fc8de90 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteMesh_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_services_v1 + + +def sample_delete_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteMeshRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py new file mode 100644 index 000000000000..eb2f26263c58 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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_services_v1 + + +async def sample_delete_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteServiceBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py new file mode 100644 index 000000000000..89cac141e765 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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_services_v1 + + +def sample_delete_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteServiceBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py new file mode 100644 index 000000000000..6ac130952227 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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_services_v1 + + +async def sample_delete_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTcpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py new file mode 100644 index 000000000000..352fb49047ba --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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_services_v1 + + +def sample_delete_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTcpRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py new file mode 100644 index 000000000000..7ae11b3a4636 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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_services_v1 + + +async def sample_delete_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTlsRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py new file mode 100644 index 000000000000..fff36a5cae1c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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_services_v1 + + +def sample_delete_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.DeleteTlsRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_DeleteTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py new file mode 100644 index 000000000000..5e7ac35316ef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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_services_v1 + + +async def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py new file mode 100644 index 000000000000..aa00f4052937 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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_services_v1 + + +def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py new file mode 100644 index 000000000000..a59cc838519c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetGateway_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_services_v1 + + +async def sample_get_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetGatewayRequest( + name="name_value", + ) + + # Make the request + response = await client.get_gateway(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py new file mode 100644 index 000000000000..35aaea2c5a4a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetGateway_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_services_v1 + + +def sample_get_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetGatewayRequest( + name="name_value", + ) + + # Make the request + response = client.get_gateway(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py new file mode 100644 index 000000000000..29598f544706 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetGrpcRoute_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_services_v1 + + +async def sample_get_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetGrpcRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_grpc_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py new file mode 100644 index 000000000000..ddb18b3086b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetGrpcRoute_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_services_v1 + + +def sample_get_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetGrpcRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_grpc_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py new file mode 100644 index 000000000000..7c3479312dae --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetHttpRoute_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_services_v1 + + +async def sample_get_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetHttpRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_http_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py new file mode 100644 index 000000000000..c744123642d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetHttpRoute_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_services_v1 + + +def sample_get_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetHttpRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_http_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py new file mode 100644 index 000000000000..263a4ec32a0b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetMesh_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_services_v1 + + +async def sample_get_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetMeshRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mesh(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py new file mode 100644 index 000000000000..3a82f422e6eb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetMesh_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_services_v1 + + +def sample_get_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetMeshRequest( + name="name_value", + ) + + # Make the request + response = client.get_mesh(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py new file mode 100644 index 000000000000..76cdcd294a2e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetServiceBinding_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_services_v1 + + +async def sample_get_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetServiceBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_binding(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py new file mode 100644 index 000000000000..5dc1744327fd --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetServiceBinding_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_services_v1 + + +def sample_get_service_binding(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetServiceBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_binding(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py new file mode 100644 index 000000000000..e82751f4caff --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetTcpRoute_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_services_v1 + + +async def sample_get_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetTcpRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tcp_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py new file mode 100644 index 000000000000..fc579ad345e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetTcpRoute_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_services_v1 + + +def sample_get_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetTcpRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_tcp_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py new file mode 100644 index 000000000000..ab3f3eddf388 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetTlsRoute_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_services_v1 + + +async def sample_get_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.GetTlsRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tls_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py new file mode 100644 index 000000000000..9f7194908f27 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_GetTlsRoute_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_services_v1 + + +def sample_get_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.GetTlsRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_tls_route(request=request) + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_GetTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py new file mode 100644 index 000000000000..d98d0c1c614c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEndpointPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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_services_v1 + + +async def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListEndpointPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py new file mode 100644 index 000000000000..39b5e3ab12b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEndpointPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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_services_v1 + + +def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListEndpointPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py new file mode 100644 index 000000000000..1826f29b8cd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGateways +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListGateways_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_services_v1 + + +async def sample_list_gateways(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListGatewaysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gateways(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListGateways_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py new file mode 100644 index 000000000000..801526ab899d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGateways +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListGateways_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_services_v1 + + +def sample_list_gateways(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListGatewaysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gateways(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListGateways_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py new file mode 100644 index 000000000000..439a5b952e25 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGrpcRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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_services_v1 + + +async def sample_list_grpc_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListGrpcRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_grpc_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListGrpcRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py new file mode 100644 index 000000000000..8773d8c7734f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGrpcRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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_services_v1 + + +def sample_list_grpc_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListGrpcRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_grpc_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListGrpcRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py new file mode 100644 index 000000000000..628c246df7ca --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHttpRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListHttpRoutes_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_services_v1 + + +async def sample_list_http_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListHttpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_http_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListHttpRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py new file mode 100644 index 000000000000..31a44971d681 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHttpRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListHttpRoutes_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_services_v1 + + +def sample_list_http_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListHttpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_http_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListHttpRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py new file mode 100644 index 000000000000..f73783501908 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMeshes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListMeshes_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_services_v1 + + +async def sample_list_meshes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListMeshesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_meshes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListMeshes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py new file mode 100644 index 000000000000..583cf57586e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMeshes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListMeshes_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_services_v1 + + +def sample_list_meshes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListMeshesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_meshes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListMeshes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py new file mode 100644 index 000000000000..f57e5a9a6e35 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListServiceBindings_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_services_v1 + + +async def sample_list_service_bindings(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListServiceBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_service_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListServiceBindings_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py new file mode 100644 index 000000000000..ab0475e0460c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListServiceBindings_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_services_v1 + + +def sample_list_service_bindings(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListServiceBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_service_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListServiceBindings_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py new file mode 100644 index 000000000000..c595de0772ba --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTcpRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListTcpRoutes_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_services_v1 + + +async def sample_list_tcp_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListTcpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tcp_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListTcpRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py new file mode 100644 index 000000000000..f96ac04d49ef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTcpRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListTcpRoutes_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_services_v1 + + +def sample_list_tcp_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListTcpRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tcp_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListTcpRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py new file mode 100644 index 000000000000..69e2dc5b3fa2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTlsRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListTlsRoutes_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_services_v1 + + +async def sample_list_tls_routes(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1.ListTlsRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tls_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListTlsRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py new file mode 100644 index 000000000000..1fbee93bef58 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTlsRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_ListTlsRoutes_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_services_v1 + + +def sample_list_tls_routes(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1.ListTlsRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tls_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkservices_v1_generated_NetworkServices_ListTlsRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py new file mode 100644 index 000000000000..0596b2a4940d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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_services_v1 + + +async def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py new file mode 100644 index 000000000000..b6d1c512b24a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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_services_v1 + + +def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py new file mode 100644 index 000000000000..5c2cee43dda9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateGateway_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_services_v1 + + +async def sample_update_gateway(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.UpdateGatewayRequest( + gateway=gateway, + ) + + # Make the request + operation = client.update_gateway(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py new file mode 100644 index 000000000000..421cd1394a65 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGateway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateGateway_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_services_v1 + + +def sample_update_gateway(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + gateway = network_services_v1.Gateway() + gateway.name = "name_value" + gateway.ports = [569, 570] + gateway.scope = "scope_value" + + request = network_services_v1.UpdateGatewayRequest( + gateway=gateway, + ) + + # Make the request + operation = client.update_gateway(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py new file mode 100644 index 000000000000..e8468acbf671 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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_services_v1 + + +async def sample_update_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateGrpcRouteRequest( + grpc_route=grpc_route, + ) + + # Make the request + operation = client.update_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py new file mode 100644 index 000000000000..3107cd333096 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGrpcRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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_services_v1 + + +def sample_update_grpc_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + grpc_route = network_services_v1.GrpcRoute() + grpc_route.name = "name_value" + grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateGrpcRouteRequest( + grpc_route=grpc_route, + ) + + # Make the request + operation = client.update_grpc_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py new file mode 100644 index 000000000000..756ea1acdea3 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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_services_v1 + + +async def sample_update_http_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateHttpRouteRequest( + http_route=http_route, + ) + + # Make the request + operation = client.update_http_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py new file mode 100644 index 000000000000..a7629cacb114 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHttpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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_services_v1 + + +def sample_update_http_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + http_route = network_services_v1.HttpRoute() + http_route.name = "name_value" + http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] + + request = network_services_v1.UpdateHttpRouteRequest( + http_route=http_route, + ) + + # Make the request + operation = client.update_http_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py new file mode 100644 index 000000000000..95ddc1f62bd1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateMesh_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_services_v1 + + +async def sample_update_mesh(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.UpdateMeshRequest( + mesh=mesh, + ) + + # Make the request + operation = client.update_mesh(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py new file mode 100644 index 000000000000..5eccc3856f4b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMesh +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateMesh_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_services_v1 + + +def sample_update_mesh(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + mesh = network_services_v1.Mesh() + mesh.name = "name_value" + + request = network_services_v1.UpdateMeshRequest( + mesh=mesh, + ) + + # Make the request + operation = client.update_mesh(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py new file mode 100644 index 000000000000..b16cd417cea1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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_services_v1 + + +async def sample_update_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.UpdateTcpRouteRequest( + tcp_route=tcp_route, + ) + + # Make the request + operation = client.update_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py new file mode 100644 index 000000000000..59012580671d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTcpRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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_services_v1 + + +def sample_update_tcp_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tcp_route = network_services_v1.TcpRoute() + tcp_route.name = "name_value" + + request = network_services_v1.UpdateTcpRouteRequest( + tcp_route=tcp_route, + ) + + # Make the request + operation = client.update_tcp_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py new file mode 100644 index 000000000000..e28a506bb2a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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_services_v1 + + +async def sample_update_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.UpdateTlsRouteRequest( + tls_route=tls_route, + ) + + # Make the request + operation = client.update_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py new file mode 100644 index 000000000000..4f1bf9472f50 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTlsRoute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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-services + + +# [START networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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_services_v1 + + +def sample_update_tls_route(): + # Create a client + client = network_services_v1.NetworkServicesClient() + + # Initialize request argument(s) + tls_route = network_services_v1.TlsRoute() + tls_route.name = "name_value" + tls_route.rules.action.destinations.service_name = "service_name_value" + + request = network_services_v1.UpdateTlsRouteRequest( + tls_route=tls_route, + ) + + # Make the request + operation = client.update_tls_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkservices_v1_generated_NetworkServices_UpdateTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json new file mode 100644 index 000000000000..5efe8fa4280b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json @@ -0,0 +1,8136 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networkservices.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-services", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.create_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.CreateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1.types.LbRouteExtension" + }, + { + "name": "lb_route_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_lb_route_extension" + }, + "description": "Sample for CreateLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_create_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_CreateLbRouteExtension_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_create_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.create_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.CreateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1.types.LbRouteExtension" + }, + { + "name": "lb_route_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_lb_route_extension" + }, + "description": "Sample for CreateLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_CreateLbRouteExtension_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.create_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.CreateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1.types.LbTrafficExtension" + }, + { + "name": "lb_traffic_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_lb_traffic_extension" + }, + "description": "Sample for CreateLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_CreateLbTrafficExtension_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.create_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.CreateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1.types.LbTrafficExtension" + }, + { + "name": "lb_traffic_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_lb_traffic_extension" + }, + "description": "Sample for CreateLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_CreateLbTrafficExtension_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.delete_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_lb_route_extension" + }, + "description": "Sample for DeleteLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_DeleteLbRouteExtension_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": "networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.delete_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_lb_route_extension" + }, + "description": "Sample for DeleteLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_DeleteLbRouteExtension_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": "networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.delete_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_lb_traffic_extension" + }, + "description": "Sample for DeleteLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.delete_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_lb_traffic_extension" + }, + "description": "Sample for DeleteLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.get_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.GetLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.LbRouteExtension", + "shortName": "get_lb_route_extension" + }, + "description": "Sample for GetLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_get_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_GetLbRouteExtension_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": "networkservices_v1_generated_dep_service_get_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.get_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.GetLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.LbRouteExtension", + "shortName": "get_lb_route_extension" + }, + "description": "Sample for GetLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_GetLbRouteExtension_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": "networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.get_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.GetLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.LbTrafficExtension", + "shortName": "get_lb_traffic_extension" + }, + "description": "Sample for GetLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_GetLbTrafficExtension_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": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.get_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.GetLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.LbTrafficExtension", + "shortName": "get_lb_traffic_extension" + }, + "description": "Sample for GetLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_GetLbTrafficExtension_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": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.list_lb_route_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.ListLbRouteExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbRouteExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager", + "shortName": "list_lb_route_extensions" + }, + "description": "Sample for ListLbRouteExtensions", + "file": "networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_ListLbRouteExtensions_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": "networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.list_lb_route_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.ListLbRouteExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbRouteExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsPager", + "shortName": "list_lb_route_extensions" + }, + "description": "Sample for ListLbRouteExtensions", + "file": "networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_ListLbRouteExtensions_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": "networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.list_lb_traffic_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.ListLbTrafficExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbTrafficExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager", + "shortName": "list_lb_traffic_extensions" + }, + "description": "Sample for ListLbTrafficExtensions", + "file": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_ListLbTrafficExtensions_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": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.list_lb_traffic_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.ListLbTrafficExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbTrafficExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsPager", + "shortName": "list_lb_traffic_extensions" + }, + "description": "Sample for ListLbTrafficExtensions", + "file": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_ListLbTrafficExtensions_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": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.update_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1.types.LbRouteExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_lb_route_extension" + }, + "description": "Sample for UpdateLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_update_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_UpdateLbRouteExtension_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_update_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.update_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1.types.LbRouteExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_lb_route_extension" + }, + "description": "Sample for UpdateLbRouteExtension", + "file": "networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_UpdateLbRouteExtension_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.update_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1.types.LbTrafficExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_lb_traffic_extension" + }, + "description": "Sample for UpdateLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_UpdateLbTrafficExtension_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1.DepServiceClient.update_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1.types.LbTrafficExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_lb_traffic_extension" + }, + "description": "Sample for UpdateLbTrafficExtension", + "file": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_DepService_UpdateLbTrafficExtension_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateEndpointPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1.types.EndpointPolicy" + }, + { + "name": "endpoint_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_endpoint_policy" + }, + "description": "Sample for CreateEndpointPolicy", + "file": "networkservices_v1_generated_network_services_create_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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": "networkservices_v1_generated_network_services_create_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateEndpointPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1.types.EndpointPolicy" + }, + { + "name": "endpoint_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_endpoint_policy" + }, + "description": "Sample for CreateEndpointPolicy", + "file": "networkservices_v1_generated_network_services_create_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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": "networkservices_v1_generated_network_services_create_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway", + "type": "google.cloud.network_services_v1.types.Gateway" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_gateway" + }, + "description": "Sample for CreateGateway", + "file": "networkservices_v1_generated_network_services_create_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateGateway_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": "networkservices_v1_generated_network_services_create_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway", + "type": "google.cloud.network_services_v1.types.Gateway" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_gateway" + }, + "description": "Sample for CreateGateway", + "file": "networkservices_v1_generated_network_services_create_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateGateway_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": "networkservices_v1_generated_network_services_create_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateGrpcRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "grpc_route", + "type": "google.cloud.network_services_v1.types.GrpcRoute" + }, + { + "name": "grpc_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_grpc_route" + }, + "description": "Sample for CreateGrpcRoute", + "file": "networkservices_v1_generated_network_services_create_grpc_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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": "networkservices_v1_generated_network_services_create_grpc_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateGrpcRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "grpc_route", + "type": "google.cloud.network_services_v1.types.GrpcRoute" + }, + { + "name": "grpc_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_grpc_route" + }, + "description": "Sample for CreateGrpcRoute", + "file": "networkservices_v1_generated_network_services_create_grpc_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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": "networkservices_v1_generated_network_services_create_grpc_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateHttpRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "http_route", + "type": "google.cloud.network_services_v1.types.HttpRoute" + }, + { + "name": "http_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_http_route" + }, + "description": "Sample for CreateHttpRoute", + "file": "networkservices_v1_generated_network_services_create_http_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateHttpRoute_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": "networkservices_v1_generated_network_services_create_http_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateHttpRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "http_route", + "type": "google.cloud.network_services_v1.types.HttpRoute" + }, + { + "name": "http_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_http_route" + }, + "description": "Sample for CreateHttpRoute", + "file": "networkservices_v1_generated_network_services_create_http_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateHttpRoute_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": "networkservices_v1_generated_network_services_create_http_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateMeshRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mesh", + "type": "google.cloud.network_services_v1.types.Mesh" + }, + { + "name": "mesh_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_mesh" + }, + "description": "Sample for CreateMesh", + "file": "networkservices_v1_generated_network_services_create_mesh_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateMesh_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": "networkservices_v1_generated_network_services_create_mesh_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateMeshRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mesh", + "type": "google.cloud.network_services_v1.types.Mesh" + }, + { + "name": "mesh_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_mesh" + }, + "description": "Sample for CreateMesh", + "file": "networkservices_v1_generated_network_services_create_mesh_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateMesh_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": "networkservices_v1_generated_network_services_create_mesh_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateServiceBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service_binding", + "type": "google.cloud.network_services_v1.types.ServiceBinding" + }, + { + "name": "service_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_service_binding" + }, + "description": "Sample for CreateServiceBinding", + "file": "networkservices_v1_generated_network_services_create_service_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateServiceBinding_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": "networkservices_v1_generated_network_services_create_service_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateServiceBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service_binding", + "type": "google.cloud.network_services_v1.types.ServiceBinding" + }, + { + "name": "service_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_service_binding" + }, + "description": "Sample for CreateServiceBinding", + "file": "networkservices_v1_generated_network_services_create_service_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateServiceBinding_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": "networkservices_v1_generated_network_services_create_service_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateTcpRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tcp_route", + "type": "google.cloud.network_services_v1.types.TcpRoute" + }, + { + "name": "tcp_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_tcp_route" + }, + "description": "Sample for CreateTcpRoute", + "file": "networkservices_v1_generated_network_services_create_tcp_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateTcpRoute_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": "networkservices_v1_generated_network_services_create_tcp_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateTcpRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tcp_route", + "type": "google.cloud.network_services_v1.types.TcpRoute" + }, + { + "name": "tcp_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_tcp_route" + }, + "description": "Sample for CreateTcpRoute", + "file": "networkservices_v1_generated_network_services_create_tcp_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateTcpRoute_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": "networkservices_v1_generated_network_services_create_tcp_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateTlsRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tls_route", + "type": "google.cloud.network_services_v1.types.TlsRoute" + }, + { + "name": "tls_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_tls_route" + }, + "description": "Sample for CreateTlsRoute", + "file": "networkservices_v1_generated_network_services_create_tls_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateTlsRoute_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": "networkservices_v1_generated_network_services_create_tls_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.CreateTlsRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tls_route", + "type": "google.cloud.network_services_v1.types.TlsRoute" + }, + { + "name": "tls_route_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_tls_route" + }, + "description": "Sample for CreateTlsRoute", + "file": "networkservices_v1_generated_network_services_create_tls_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_CreateTlsRoute_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": "networkservices_v1_generated_network_services_create_tls_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_endpoint_policy" + }, + "description": "Sample for DeleteEndpointPolicy", + "file": "networkservices_v1_generated_network_services_delete_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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": "networkservices_v1_generated_network_services_delete_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_endpoint_policy" + }, + "description": "Sample for DeleteEndpointPolicy", + "file": "networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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": "networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteGatewayRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_gateway" + }, + "description": "Sample for DeleteGateway", + "file": "networkservices_v1_generated_network_services_delete_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGateway_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": "networkservices_v1_generated_network_services_delete_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteGatewayRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_gateway" + }, + "description": "Sample for DeleteGateway", + "file": "networkservices_v1_generated_network_services_delete_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGateway_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": "networkservices_v1_generated_network_services_delete_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteGrpcRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_grpc_route" + }, + "description": "Sample for DeleteGrpcRoute", + "file": "networkservices_v1_generated_network_services_delete_grpc_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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": "networkservices_v1_generated_network_services_delete_grpc_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteGrpcRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_grpc_route" + }, + "description": "Sample for DeleteGrpcRoute", + "file": "networkservices_v1_generated_network_services_delete_grpc_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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": "networkservices_v1_generated_network_services_delete_grpc_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteHttpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_http_route" + }, + "description": "Sample for DeleteHttpRoute", + "file": "networkservices_v1_generated_network_services_delete_http_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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": "networkservices_v1_generated_network_services_delete_http_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteHttpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_http_route" + }, + "description": "Sample for DeleteHttpRoute", + "file": "networkservices_v1_generated_network_services_delete_http_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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": "networkservices_v1_generated_network_services_delete_http_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteMeshRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mesh" + }, + "description": "Sample for DeleteMesh", + "file": "networkservices_v1_generated_network_services_delete_mesh_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteMesh_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": "networkservices_v1_generated_network_services_delete_mesh_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteMeshRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mesh" + }, + "description": "Sample for DeleteMesh", + "file": "networkservices_v1_generated_network_services_delete_mesh_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteMesh_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": "networkservices_v1_generated_network_services_delete_mesh_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteServiceBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_service_binding" + }, + "description": "Sample for DeleteServiceBinding", + "file": "networkservices_v1_generated_network_services_delete_service_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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": "networkservices_v1_generated_network_services_delete_service_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteServiceBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_service_binding" + }, + "description": "Sample for DeleteServiceBinding", + "file": "networkservices_v1_generated_network_services_delete_service_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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": "networkservices_v1_generated_network_services_delete_service_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteTcpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_tcp_route" + }, + "description": "Sample for DeleteTcpRoute", + "file": "networkservices_v1_generated_network_services_delete_tcp_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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": "networkservices_v1_generated_network_services_delete_tcp_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteTcpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_tcp_route" + }, + "description": "Sample for DeleteTcpRoute", + "file": "networkservices_v1_generated_network_services_delete_tcp_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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": "networkservices_v1_generated_network_services_delete_tcp_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteTlsRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_tls_route" + }, + "description": "Sample for DeleteTlsRoute", + "file": "networkservices_v1_generated_network_services_delete_tls_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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": "networkservices_v1_generated_network_services_delete_tls_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.DeleteTlsRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_tls_route" + }, + "description": "Sample for DeleteTlsRoute", + "file": "networkservices_v1_generated_network_services_delete_tls_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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": "networkservices_v1_generated_network_services_delete_tls_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.EndpointPolicy", + "shortName": "get_endpoint_policy" + }, + "description": "Sample for GetEndpointPolicy", + "file": "networkservices_v1_generated_network_services_get_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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": "networkservices_v1_generated_network_services_get_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.EndpointPolicy", + "shortName": "get_endpoint_policy" + }, + "description": "Sample for GetEndpointPolicy", + "file": "networkservices_v1_generated_network_services_get_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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": "networkservices_v1_generated_network_services_get_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetGatewayRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.Gateway", + "shortName": "get_gateway" + }, + "description": "Sample for GetGateway", + "file": "networkservices_v1_generated_network_services_get_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetGateway_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": "networkservices_v1_generated_network_services_get_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetGatewayRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.Gateway", + "shortName": "get_gateway" + }, + "description": "Sample for GetGateway", + "file": "networkservices_v1_generated_network_services_get_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetGateway_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": "networkservices_v1_generated_network_services_get_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetGrpcRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.GrpcRoute", + "shortName": "get_grpc_route" + }, + "description": "Sample for GetGrpcRoute", + "file": "networkservices_v1_generated_network_services_get_grpc_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetGrpcRoute_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": "networkservices_v1_generated_network_services_get_grpc_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetGrpcRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.GrpcRoute", + "shortName": "get_grpc_route" + }, + "description": "Sample for GetGrpcRoute", + "file": "networkservices_v1_generated_network_services_get_grpc_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetGrpcRoute_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": "networkservices_v1_generated_network_services_get_grpc_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetHttpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.HttpRoute", + "shortName": "get_http_route" + }, + "description": "Sample for GetHttpRoute", + "file": "networkservices_v1_generated_network_services_get_http_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetHttpRoute_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": "networkservices_v1_generated_network_services_get_http_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetHttpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.HttpRoute", + "shortName": "get_http_route" + }, + "description": "Sample for GetHttpRoute", + "file": "networkservices_v1_generated_network_services_get_http_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetHttpRoute_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": "networkservices_v1_generated_network_services_get_http_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetMeshRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.Mesh", + "shortName": "get_mesh" + }, + "description": "Sample for GetMesh", + "file": "networkservices_v1_generated_network_services_get_mesh_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetMesh_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": "networkservices_v1_generated_network_services_get_mesh_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetMeshRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.Mesh", + "shortName": "get_mesh" + }, + "description": "Sample for GetMesh", + "file": "networkservices_v1_generated_network_services_get_mesh_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetMesh_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": "networkservices_v1_generated_network_services_get_mesh_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetServiceBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.ServiceBinding", + "shortName": "get_service_binding" + }, + "description": "Sample for GetServiceBinding", + "file": "networkservices_v1_generated_network_services_get_service_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetServiceBinding_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": "networkservices_v1_generated_network_services_get_service_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_service_binding", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetServiceBinding", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetServiceBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetServiceBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.ServiceBinding", + "shortName": "get_service_binding" + }, + "description": "Sample for GetServiceBinding", + "file": "networkservices_v1_generated_network_services_get_service_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetServiceBinding_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": "networkservices_v1_generated_network_services_get_service_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetTcpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.TcpRoute", + "shortName": "get_tcp_route" + }, + "description": "Sample for GetTcpRoute", + "file": "networkservices_v1_generated_network_services_get_tcp_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetTcpRoute_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": "networkservices_v1_generated_network_services_get_tcp_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetTcpRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.TcpRoute", + "shortName": "get_tcp_route" + }, + "description": "Sample for GetTcpRoute", + "file": "networkservices_v1_generated_network_services_get_tcp_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetTcpRoute_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": "networkservices_v1_generated_network_services_get_tcp_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetTlsRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.TlsRoute", + "shortName": "get_tls_route" + }, + "description": "Sample for GetTlsRoute", + "file": "networkservices_v1_generated_network_services_get_tls_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetTlsRoute_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": "networkservices_v1_generated_network_services_get_tls_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.GetTlsRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.types.TlsRoute", + "shortName": "get_tls_route" + }, + "description": "Sample for GetTlsRoute", + "file": "networkservices_v1_generated_network_services_get_tls_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_GetTlsRoute_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": "networkservices_v1_generated_network_services_get_tls_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_endpoint_policies", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListEndpointPolicies", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListEndpointPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListEndpointPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesAsyncPager", + "shortName": "list_endpoint_policies" + }, + "description": "Sample for ListEndpointPolicies", + "file": "networkservices_v1_generated_network_services_list_endpoint_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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": "networkservices_v1_generated_network_services_list_endpoint_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_endpoint_policies", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListEndpointPolicies", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListEndpointPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListEndpointPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesPager", + "shortName": "list_endpoint_policies" + }, + "description": "Sample for ListEndpointPolicies", + "file": "networkservices_v1_generated_network_services_list_endpoint_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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": "networkservices_v1_generated_network_services_list_endpoint_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_gateways", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGateways", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListGateways" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListGatewaysRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysAsyncPager", + "shortName": "list_gateways" + }, + "description": "Sample for ListGateways", + "file": "networkservices_v1_generated_network_services_list_gateways_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListGateways_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": "networkservices_v1_generated_network_services_list_gateways_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_gateways", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGateways", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListGateways" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListGatewaysRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysPager", + "shortName": "list_gateways" + }, + "description": "Sample for ListGateways", + "file": "networkservices_v1_generated_network_services_list_gateways_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListGateways_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": "networkservices_v1_generated_network_services_list_gateways_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_grpc_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGrpcRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListGrpcRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListGrpcRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesAsyncPager", + "shortName": "list_grpc_routes" + }, + "description": "Sample for ListGrpcRoutes", + "file": "networkservices_v1_generated_network_services_list_grpc_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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": "networkservices_v1_generated_network_services_list_grpc_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_grpc_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGrpcRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListGrpcRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListGrpcRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesPager", + "shortName": "list_grpc_routes" + }, + "description": "Sample for ListGrpcRoutes", + "file": "networkservices_v1_generated_network_services_list_grpc_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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": "networkservices_v1_generated_network_services_list_grpc_routes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_http_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListHttpRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListHttpRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListHttpRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesAsyncPager", + "shortName": "list_http_routes" + }, + "description": "Sample for ListHttpRoutes", + "file": "networkservices_v1_generated_network_services_list_http_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListHttpRoutes_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": "networkservices_v1_generated_network_services_list_http_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_http_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListHttpRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListHttpRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListHttpRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesPager", + "shortName": "list_http_routes" + }, + "description": "Sample for ListHttpRoutes", + "file": "networkservices_v1_generated_network_services_list_http_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListHttpRoutes_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": "networkservices_v1_generated_network_services_list_http_routes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_meshes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListMeshes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListMeshes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListMeshesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListMeshesAsyncPager", + "shortName": "list_meshes" + }, + "description": "Sample for ListMeshes", + "file": "networkservices_v1_generated_network_services_list_meshes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListMeshes_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": "networkservices_v1_generated_network_services_list_meshes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_meshes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListMeshes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListMeshes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListMeshesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListMeshesPager", + "shortName": "list_meshes" + }, + "description": "Sample for ListMeshes", + "file": "networkservices_v1_generated_network_services_list_meshes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListMeshes_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": "networkservices_v1_generated_network_services_list_meshes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_service_bindings", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListServiceBindings", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListServiceBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListServiceBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsAsyncPager", + "shortName": "list_service_bindings" + }, + "description": "Sample for ListServiceBindings", + "file": "networkservices_v1_generated_network_services_list_service_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListServiceBindings_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": "networkservices_v1_generated_network_services_list_service_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_service_bindings", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListServiceBindings", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListServiceBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListServiceBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsPager", + "shortName": "list_service_bindings" + }, + "description": "Sample for ListServiceBindings", + "file": "networkservices_v1_generated_network_services_list_service_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListServiceBindings_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": "networkservices_v1_generated_network_services_list_service_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_tcp_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTcpRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListTcpRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListTcpRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesAsyncPager", + "shortName": "list_tcp_routes" + }, + "description": "Sample for ListTcpRoutes", + "file": "networkservices_v1_generated_network_services_list_tcp_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListTcpRoutes_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": "networkservices_v1_generated_network_services_list_tcp_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_tcp_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTcpRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListTcpRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListTcpRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesPager", + "shortName": "list_tcp_routes" + }, + "description": "Sample for ListTcpRoutes", + "file": "networkservices_v1_generated_network_services_list_tcp_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListTcpRoutes_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": "networkservices_v1_generated_network_services_list_tcp_routes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_tls_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTlsRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListTlsRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListTlsRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesAsyncPager", + "shortName": "list_tls_routes" + }, + "description": "Sample for ListTlsRoutes", + "file": "networkservices_v1_generated_network_services_list_tls_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListTlsRoutes_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": "networkservices_v1_generated_network_services_list_tls_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_tls_routes", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTlsRoutes", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListTlsRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.ListTlsRoutesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesPager", + "shortName": "list_tls_routes" + }, + "description": "Sample for ListTlsRoutes", + "file": "networkservices_v1_generated_network_services_list_tls_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_ListTlsRoutes_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": "networkservices_v1_generated_network_services_list_tls_routes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1.types.EndpointPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_endpoint_policy" + }, + "description": "Sample for UpdateEndpointPolicy", + "file": "networkservices_v1_generated_network_services_update_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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": "networkservices_v1_generated_network_services_update_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1.types.EndpointPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_endpoint_policy" + }, + "description": "Sample for UpdateEndpointPolicy", + "file": "networkservices_v1_generated_network_services_update_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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": "networkservices_v1_generated_network_services_update_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateGatewayRequest" + }, + { + "name": "gateway", + "type": "google.cloud.network_services_v1.types.Gateway" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_gateway" + }, + "description": "Sample for UpdateGateway", + "file": "networkservices_v1_generated_network_services_update_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGateway_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": "networkservices_v1_generated_network_services_update_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_gateway", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGateway", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateGatewayRequest" + }, + { + "name": "gateway", + "type": "google.cloud.network_services_v1.types.Gateway" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_gateway" + }, + "description": "Sample for UpdateGateway", + "file": "networkservices_v1_generated_network_services_update_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGateway_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": "networkservices_v1_generated_network_services_update_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateGrpcRouteRequest" + }, + { + "name": "grpc_route", + "type": "google.cloud.network_services_v1.types.GrpcRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_grpc_route" + }, + "description": "Sample for UpdateGrpcRoute", + "file": "networkservices_v1_generated_network_services_update_grpc_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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": "networkservices_v1_generated_network_services_update_grpc_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_grpc_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGrpcRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateGrpcRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateGrpcRouteRequest" + }, + { + "name": "grpc_route", + "type": "google.cloud.network_services_v1.types.GrpcRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_grpc_route" + }, + "description": "Sample for UpdateGrpcRoute", + "file": "networkservices_v1_generated_network_services_update_grpc_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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": "networkservices_v1_generated_network_services_update_grpc_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateHttpRouteRequest" + }, + { + "name": "http_route", + "type": "google.cloud.network_services_v1.types.HttpRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_http_route" + }, + "description": "Sample for UpdateHttpRoute", + "file": "networkservices_v1_generated_network_services_update_http_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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": "networkservices_v1_generated_network_services_update_http_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_http_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateHttpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateHttpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateHttpRouteRequest" + }, + { + "name": "http_route", + "type": "google.cloud.network_services_v1.types.HttpRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_http_route" + }, + "description": "Sample for UpdateHttpRoute", + "file": "networkservices_v1_generated_network_services_update_http_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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": "networkservices_v1_generated_network_services_update_http_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateMeshRequest" + }, + { + "name": "mesh", + "type": "google.cloud.network_services_v1.types.Mesh" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_mesh" + }, + "description": "Sample for UpdateMesh", + "file": "networkservices_v1_generated_network_services_update_mesh_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateMesh_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": "networkservices_v1_generated_network_services_update_mesh_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_mesh", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateMesh", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateMesh" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateMeshRequest" + }, + { + "name": "mesh", + "type": "google.cloud.network_services_v1.types.Mesh" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_mesh" + }, + "description": "Sample for UpdateMesh", + "file": "networkservices_v1_generated_network_services_update_mesh_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateMesh_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": "networkservices_v1_generated_network_services_update_mesh_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateTcpRouteRequest" + }, + { + "name": "tcp_route", + "type": "google.cloud.network_services_v1.types.TcpRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_tcp_route" + }, + "description": "Sample for UpdateTcpRoute", + "file": "networkservices_v1_generated_network_services_update_tcp_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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": "networkservices_v1_generated_network_services_update_tcp_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_tcp_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTcpRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateTcpRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateTcpRouteRequest" + }, + { + "name": "tcp_route", + "type": "google.cloud.network_services_v1.types.TcpRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_tcp_route" + }, + "description": "Sample for UpdateTcpRoute", + "file": "networkservices_v1_generated_network_services_update_tcp_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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": "networkservices_v1_generated_network_services_update_tcp_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateTlsRouteRequest" + }, + { + "name": "tls_route", + "type": "google.cloud.network_services_v1.types.TlsRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_tls_route" + }, + "description": "Sample for UpdateTlsRoute", + "file": "networkservices_v1_generated_network_services_update_tls_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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": "networkservices_v1_generated_network_services_update_tls_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_tls_route", + "method": { + "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTlsRoute", + "service": { + "fullName": "google.cloud.networkservices.v1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateTlsRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1.types.UpdateTlsRouteRequest" + }, + { + "name": "tls_route", + "type": "google.cloud.network_services_v1.types.TlsRoute" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_tls_route" + }, + "description": "Sample for UpdateTlsRoute", + "file": "networkservices_v1_generated_network_services_update_tls_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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": "networkservices_v1_generated_network_services_update_tls_route_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py b/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py new file mode 100644 index 000000000000..22a35f3c0c14 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py @@ -0,0 +1,224 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_servicesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_endpoint_policy': ('parent', 'endpoint_policy_id', 'endpoint_policy', ), + 'create_gateway': ('parent', 'gateway_id', 'gateway', ), + 'create_grpc_route': ('parent', 'grpc_route_id', 'grpc_route', ), + 'create_http_route': ('parent', 'http_route_id', 'http_route', ), + 'create_lb_route_extension': ('parent', 'lb_route_extension_id', 'lb_route_extension', 'request_id', ), + 'create_lb_traffic_extension': ('parent', 'lb_traffic_extension_id', 'lb_traffic_extension', 'request_id', ), + 'create_mesh': ('parent', 'mesh_id', 'mesh', ), + 'create_service_binding': ('parent', 'service_binding_id', 'service_binding', ), + 'create_tcp_route': ('parent', 'tcp_route_id', 'tcp_route', ), + 'create_tls_route': ('parent', 'tls_route_id', 'tls_route', ), + 'delete_endpoint_policy': ('name', ), + 'delete_gateway': ('name', ), + 'delete_grpc_route': ('name', ), + 'delete_http_route': ('name', ), + 'delete_lb_route_extension': ('name', 'request_id', ), + 'delete_lb_traffic_extension': ('name', 'request_id', ), + 'delete_mesh': ('name', ), + 'delete_service_binding': ('name', ), + 'delete_tcp_route': ('name', ), + 'delete_tls_route': ('name', ), + 'get_endpoint_policy': ('name', ), + 'get_gateway': ('name', ), + 'get_grpc_route': ('name', ), + 'get_http_route': ('name', ), + 'get_lb_route_extension': ('name', ), + 'get_lb_traffic_extension': ('name', ), + 'get_mesh': ('name', ), + 'get_service_binding': ('name', ), + 'get_tcp_route': ('name', ), + 'get_tls_route': ('name', ), + 'list_endpoint_policies': ('parent', 'page_size', 'page_token', ), + 'list_gateways': ('parent', 'page_size', 'page_token', ), + 'list_grpc_routes': ('parent', 'page_size', 'page_token', ), + 'list_http_routes': ('parent', 'page_size', 'page_token', ), + 'list_lb_route_extensions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_lb_traffic_extensions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_meshes': ('parent', 'page_size', 'page_token', ), + 'list_service_bindings': ('parent', 'page_size', 'page_token', ), + 'list_tcp_routes': ('parent', 'page_size', 'page_token', ), + 'list_tls_routes': ('parent', 'page_size', 'page_token', ), + 'update_endpoint_policy': ('endpoint_policy', 'update_mask', ), + 'update_gateway': ('gateway', 'update_mask', ), + 'update_grpc_route': ('grpc_route', 'update_mask', ), + 'update_http_route': ('http_route', 'update_mask', ), + 'update_lb_route_extension': ('lb_route_extension', 'update_mask', 'request_id', ), + 'update_lb_traffic_extension': ('lb_traffic_extension', 'update_mask', 'request_id', ), + 'update_mesh': ('mesh', 'update_mask', ), + 'update_tcp_route': ('tcp_route', 'update_mask', ), + 'update_tls_route': ('tls_route', '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_servicesCallTransformer(), +): + """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_services 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-services/v1/setup.py b/owl-bot-staging/google-cloud-network-services/v1/setup.py new file mode 100644 index 000000000000..be59630732e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/setup.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services' + + +description = "Google Cloud Network Services API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_services/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..4cd2782277d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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.0dev", +# 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.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/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-services/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/tests/unit/gapic/network_services_v1/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py new file mode 100644 index 000000000000..97c8fdf3643f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py @@ -0,0 +1,10386 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from 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 + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_services_v1.services.dep_service import DepServiceAsyncClient +from google.cloud.network_services_v1.services.dep_service import DepServiceClient +from google.cloud.network_services_v1.services.dep_service import pagers +from google.cloud.network_services_v1.services.dep_service import transports +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import dep +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# 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 DepServiceClient._get_default_mtls_endpoint(None) is None + assert DepServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DepServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DepServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DepServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DepServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert DepServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert DepServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert DepServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + DepServiceClient._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 DepServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert DepServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert DepServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + DepServiceClient._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 DepServiceClient._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 DepServiceClient._get_client_cert_source(None, False) is None + assert DepServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert DepServiceClient._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 DepServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert DepServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) +@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = DepServiceClient._DEFAULT_UNIVERSE + default_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert DepServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert DepServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DepServiceClient.DEFAULT_MTLS_ENDPOINT + assert DepServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert DepServiceClient._get_api_endpoint(None, None, default_universe, "always") == DepServiceClient.DEFAULT_MTLS_ENDPOINT + assert DepServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DepServiceClient.DEFAULT_MTLS_ENDPOINT + assert DepServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert DepServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + DepServiceClient._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 DepServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert DepServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert DepServiceClient._get_universe_domain(None, None) == DepServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + DepServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), + (DepServiceClient, transports.DepServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DepServiceClient, "grpc"), + (DepServiceAsyncClient, "grpc_asyncio"), + (DepServiceClient, "rest"), +]) +def test_dep_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 == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkservices.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DepServiceGrpcTransport, "grpc"), + (transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DepServiceRestTransport, "rest"), +]) +def test_dep_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", [ + (DepServiceClient, "grpc"), + (DepServiceAsyncClient, "grpc_asyncio"), + (DepServiceClient, "rest"), +]) +def test_dep_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 == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkservices.googleapis.com' + ) + + +def test_dep_service_client_get_transport_class(): + transport = DepServiceClient.get_transport_class() + available_transports = [ + transports.DepServiceGrpcTransport, + transports.DepServiceRestTransport, + ] + assert transport in available_transports + + transport = DepServiceClient.get_transport_class("grpc") + assert transport == transports.DepServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DepServiceClient, transports.DepServiceRestTransport, "rest"), +]) +@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) +@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) +def test_dep_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(DepServiceClient, '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(DepServiceClient, '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", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "true"), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "false"), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DepServiceClient, transports.DepServiceRestTransport, "rest", "true"), + (DepServiceClient, transports.DepServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) +@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dep_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", [ + DepServiceClient, DepServiceAsyncClient +]) +@mock.patch.object(DepServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DepServiceClient)) +@mock.patch.object(DepServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DepServiceAsyncClient)) +def test_dep_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", [ + DepServiceClient, DepServiceAsyncClient +]) +@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) +@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) +def test_dep_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DepServiceClient._DEFAULT_UNIVERSE + default_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DepServiceClient._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", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DepServiceClient, transports.DepServiceRestTransport, "rest"), +]) +def test_dep_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", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DepServiceClient, transports.DepServiceRestTransport, "rest", None), +]) +def test_dep_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_dep_service_client_client_options_from_dict(): + with mock.patch('google.cloud.network_services_v1.services.dep_service.transports.DepServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DepServiceClient( + 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", [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dep_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( + "networkservices.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="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + dep.ListLbTrafficExtensionsRequest, + dict, +]) +def test_list_lb_traffic_extensions(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_lb_traffic_extensions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_lb_traffic_extensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbTrafficExtensionsRequest() + + +def test_list_lb_traffic_extensions_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 = DepServiceClient( + 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 = dep.ListLbTrafficExtensionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_lb_traffic_extensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbTrafficExtensionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_lb_traffic_extensions_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 = DepServiceClient( + 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_lb_traffic_extensions 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_lb_traffic_extensions] = mock_rpc + request = {} + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_traffic_extensions(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_lb_traffic_extensions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_lb_traffic_extensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbTrafficExtensionsRequest() + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_traffic_extensions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_lb_traffic_extensions] = mock_object + + request = {} + await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_lb_traffic_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async(transport: str = 'grpc_asyncio', request_type=dep.ListLbTrafficExtensionsRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async_from_dict(): + await test_list_lb_traffic_extensions_async(request_type=dict) + + +def test_list_lb_traffic_extensions_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbTrafficExtensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + call.return_value = dep.ListLbTrafficExtensionsResponse() + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_lb_traffic_extensions_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbTrafficExtensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse()) + await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_lb_traffic_extensions_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_lb_traffic_extensions( + 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_lb_traffic_extensions_flattened_error(): + client = DepServiceClient( + 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_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_lb_traffic_extensions( + 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_lb_traffic_extensions_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent='parent_value', + ) + + +def test_list_lb_traffic_extensions_pager(transport_name: str = "grpc"): + client = DepServiceClient( + 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_lb_traffic_extensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token='abc', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token='def', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_lb_traffic_extensions(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbTrafficExtension) + for i in results) +def test_list_lb_traffic_extensions_pages(transport_name: str = "grpc"): + client = DepServiceClient( + 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_lb_traffic_extensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token='abc', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token='def', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_lb_traffic_extensions(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_lb_traffic_extensions_async_pager(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token='abc', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token='def', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_lb_traffic_extensions(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, dep.LbTrafficExtension) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async_pages(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token='abc', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token='def', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + 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_lb_traffic_extensions(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", [ + dep.GetLbTrafficExtensionRequest, + dict, +]) +def test_get_lb_traffic_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + response = client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.GetLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_traffic_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbTrafficExtensionRequest() + + +def test_get_lb_traffic_extension_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 = DepServiceClient( + 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 = dep.GetLbTrafficExtensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbTrafficExtensionRequest( + name='name_value', + ) + +def test_get_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + request = {} + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + )) + response = await client.get_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbTrafficExtensionRequest() + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_traffic_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_lb_traffic_extension] = mock_object + + request = {} + await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.GetLbTrafficExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + )) + response = await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.GetLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_async_from_dict(): + await test_get_lb_traffic_extension_async(request_type=dict) + + +def test_get_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbTrafficExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + call.return_value = dep.LbTrafficExtension() + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbTrafficExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension()) + await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_lb_traffic_extension( + 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_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_lb_traffic_extension( + 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_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.CreateLbTrafficExtensionRequest, + dict, +]) +def test_create_lb_traffic_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_traffic_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbTrafficExtensionRequest() + + +def test_create_lb_traffic_extension_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 = DepServiceClient( + 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 = dep.CreateLbTrafficExtensionRequest( + parent='parent_value', + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbTrafficExtensionRequest( + parent='parent_value', + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + +def test_create_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + request = {} + client.create_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__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_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbTrafficExtensionRequest() + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_traffic_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_lb_traffic_extension] = mock_object + + request = {} + await client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.CreateLbTrafficExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__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_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.CreateLbTrafficExtensionRequest() + 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_lb_traffic_extension_async_from_dict(): + await test_create_lb_traffic_extension_async(request_type=dict) + + +def test_create_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbTrafficExtensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbTrafficExtensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__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_lb_traffic_extension( + parent='parent_value', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_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].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name='name_value') + assert arg == mock_val + arg = args[0].lb_traffic_extension_id + mock_val = 'lb_traffic_extension_id_value' + assert arg == mock_val + + +def test_create_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent='parent_value', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), + '__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_lb_traffic_extension( + parent='parent_value', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_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].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name='name_value') + assert arg == mock_val + arg = args[0].lb_traffic_extension_id + mock_val = 'lb_traffic_extension_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent='parent_value', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.UpdateLbTrafficExtensionRequest, + dict, +]) +def test_update_lb_traffic_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_traffic_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbTrafficExtensionRequest() + + +def test_update_lb_traffic_extension_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 = DepServiceClient( + 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 = dep.UpdateLbTrafficExtensionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbTrafficExtensionRequest( + ) + +def test_update_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + request = {} + client.update_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__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_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbTrafficExtensionRequest() + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_traffic_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_lb_traffic_extension] = mock_object + + request = {} + await client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.UpdateLbTrafficExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__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_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbTrafficExtensionRequest() + 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_lb_traffic_extension_async_from_dict(): + await test_update_lb_traffic_extension_async(request_type=dict) + + +def test_update_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbTrafficExtensionRequest() + + request.lb_traffic_extension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'lb_traffic_extension.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbTrafficExtensionRequest() + + request.lb_traffic_extension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'lb_traffic_extension.name=name_value', + ) in kw['metadata'] + + +def test_update_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__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_lb_traffic_extension( + lb_traffic_extension=dep.LbTrafficExtension(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].lb_traffic_extension + mock_val = dep.LbTrafficExtension(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_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), + '__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_lb_traffic_extension( + lb_traffic_extension=dep.LbTrafficExtension(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].lb_traffic_extension + mock_val = dep.LbTrafficExtension(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_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + dep.DeleteLbTrafficExtensionRequest, + dict, +]) +def test_delete_lb_traffic_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_traffic_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbTrafficExtensionRequest() + + +def test_delete_lb_traffic_extension_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 = DepServiceClient( + 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 = dep.DeleteLbTrafficExtensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbTrafficExtensionRequest( + name='name_value', + ) + +def test_delete_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + request = {} + client.delete_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__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_lb_traffic_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbTrafficExtensionRequest() + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_traffic_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_lb_traffic_extension] = mock_object + + request = {} + await client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.DeleteLbTrafficExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), + '__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_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbTrafficExtensionRequest() + 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_lb_traffic_extension_async_from_dict(): + await test_delete_lb_traffic_extension_async(request_type=dict) + + +def test_delete_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbTrafficExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbTrafficExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__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_lb_traffic_extension( + 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_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), + '__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_lb_traffic_extension( + 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_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.ListLbRouteExtensionsRequest, + dict, +]) +def test_list_lb_route_extensions(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.ListLbRouteExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_lb_route_extensions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_lb_route_extensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbRouteExtensionsRequest() + + +def test_list_lb_route_extensions_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 = DepServiceClient( + 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 = dep.ListLbRouteExtensionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_lb_route_extensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbRouteExtensionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_lb_route_extensions_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 = DepServiceClient( + 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_lb_route_extensions 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_lb_route_extensions] = mock_rpc + request = {} + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_route_extensions(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_lb_route_extensions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_lb_route_extensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.ListLbRouteExtensionsRequest() + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_route_extensions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_lb_route_extensions] = mock_object + + request = {} + await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_lb_route_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async(transport: str = 'grpc_asyncio', request_type=dep.ListLbRouteExtensionsRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.ListLbRouteExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async_from_dict(): + await test_list_lb_route_extensions_async(request_type=dict) + + +def test_list_lb_route_extensions_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbRouteExtensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + call.return_value = dep.ListLbRouteExtensionsResponse() + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_lb_route_extensions_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbRouteExtensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse()) + await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_lb_route_extensions_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_lb_route_extensions( + 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_lb_route_extensions_flattened_error(): + client = DepServiceClient( + 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_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_lb_route_extensions( + 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_lb_route_extensions_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent='parent_value', + ) + + +def test_list_lb_route_extensions_pager(transport_name: str = "grpc"): + client = DepServiceClient( + 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_lb_route_extensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token='abc', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token='def', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_lb_route_extensions(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbRouteExtension) + for i in results) +def test_list_lb_route_extensions_pages(transport_name: str = "grpc"): + client = DepServiceClient( + 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_lb_route_extensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token='abc', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token='def', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_lb_route_extensions(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_lb_route_extensions_async_pager(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token='abc', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token='def', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_lb_route_extensions(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, dep.LbRouteExtension) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async_pages(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token='abc', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token='def', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + 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_lb_route_extensions(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", [ + dep.GetLbRouteExtensionRequest, + dict, +]) +def test_get_lb_route_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + response = client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.GetLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_route_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbRouteExtensionRequest() + + +def test_get_lb_route_extension_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 = DepServiceClient( + 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 = dep.GetLbRouteExtensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbRouteExtensionRequest( + name='name_value', + ) + +def test_get_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + request = {} + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_route_extension(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_lb_route_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + )) + response = await client.get_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.GetLbRouteExtensionRequest() + +@pytest.mark.asyncio +async def test_get_lb_route_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_route_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_lb_route_extension] = mock_object + + request = {} + await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.GetLbRouteExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + )) + response = await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.GetLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +@pytest.mark.asyncio +async def test_get_lb_route_extension_async_from_dict(): + await test_get_lb_route_extension_async(request_type=dict) + + +def test_get_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbRouteExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + call.return_value = dep.LbRouteExtension() + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbRouteExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension()) + await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_lb_route_extension( + 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_lb_route_extension_flattened_error(): + client = DepServiceClient( + 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_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_lb_route_extension( + 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_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.CreateLbRouteExtensionRequest, + dict, +]) +def test_create_lb_route_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.CreateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_route_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbRouteExtensionRequest() + + +def test_create_lb_route_extension_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 = DepServiceClient( + 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 = dep.CreateLbRouteExtensionRequest( + parent='parent_value', + lb_route_extension_id='lb_route_extension_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbRouteExtensionRequest( + parent='parent_value', + lb_route_extension_id='lb_route_extension_id_value', + ) + +def test_create_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + request = {} + client.create_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__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_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.CreateLbRouteExtensionRequest() + +@pytest.mark.asyncio +async def test_create_lb_route_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_route_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_lb_route_extension] = mock_object + + request = {} + await client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.CreateLbRouteExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__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_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.CreateLbRouteExtensionRequest() + 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_lb_route_extension_async_from_dict(): + await test_create_lb_route_extension_async(request_type=dict) + + +def test_create_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbRouteExtensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbRouteExtensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__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_lb_route_extension( + parent='parent_value', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_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].lb_route_extension + mock_val = dep.LbRouteExtension(name='name_value') + assert arg == mock_val + arg = args[0].lb_route_extension_id + mock_val = 'lb_route_extension_id_value' + assert arg == mock_val + + +def test_create_lb_route_extension_flattened_error(): + client = DepServiceClient( + 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_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent='parent_value', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_id_value', + ) + +@pytest.mark.asyncio +async def test_create_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), + '__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_lb_route_extension( + parent='parent_value', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_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].lb_route_extension + mock_val = dep.LbRouteExtension(name='name_value') + assert arg == mock_val + arg = args[0].lb_route_extension_id + mock_val = 'lb_route_extension_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent='parent_value', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.UpdateLbRouteExtensionRequest, + dict, +]) +def test_update_lb_route_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_route_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbRouteExtensionRequest() + + +def test_update_lb_route_extension_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 = DepServiceClient( + 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 = dep.UpdateLbRouteExtensionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbRouteExtensionRequest( + ) + +def test_update_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + request = {} + client.update_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__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_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.UpdateLbRouteExtensionRequest() + +@pytest.mark.asyncio +async def test_update_lb_route_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_route_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_lb_route_extension] = mock_object + + request = {} + await client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.UpdateLbRouteExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__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_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbRouteExtensionRequest() + 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_lb_route_extension_async_from_dict(): + await test_update_lb_route_extension_async(request_type=dict) + + +def test_update_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbRouteExtensionRequest() + + request.lb_route_extension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'lb_route_extension.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbRouteExtensionRequest() + + request.lb_route_extension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'lb_route_extension.name=name_value', + ) in kw['metadata'] + + +def test_update_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__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_lb_route_extension( + lb_route_extension=dep.LbRouteExtension(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].lb_route_extension + mock_val = dep.LbRouteExtension(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_lb_route_extension_flattened_error(): + client = DepServiceClient( + 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_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), + '__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_lb_route_extension( + lb_route_extension=dep.LbRouteExtension(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].lb_route_extension + mock_val = dep.LbRouteExtension(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_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + dep.DeleteLbRouteExtensionRequest, + dict, +]) +def test_delete_lb_route_extension(request_type, transport: str = 'grpc'): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_route_extension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbRouteExtensionRequest() + + +def test_delete_lb_route_extension_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 = DepServiceClient( + 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 = dep.DeleteLbRouteExtensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbRouteExtensionRequest( + name='name_value', + ) + +def test_delete_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + request = {} + client.delete_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__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_lb_route_extension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dep.DeleteLbRouteExtensionRequest() + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_lb_route_extension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_lb_route_extension] = mock_object + + request = {} + await client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.DeleteLbRouteExtensionRequest): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_lb_route_extension), + '__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_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbRouteExtensionRequest() + 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_lb_route_extension_async_from_dict(): + await test_delete_lb_route_extension_async(request_type=dict) + + +def test_delete_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbRouteExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbRouteExtensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__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_lb_route_extension( + 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_lb_route_extension_flattened_error(): + client = DepServiceClient( + 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_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), + '__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_lb_route_extension( + 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_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + dep.ListLbTrafficExtensionsRequest, + dict, +]) +def test_list_lb_traffic_extensions_rest(request_type): + client = DepServiceClient( + 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 = dep.ListLbTrafficExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_lb_traffic_extensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_lb_traffic_extensions_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 = DepServiceClient( + 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_lb_traffic_extensions 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_lb_traffic_extensions] = mock_rpc + + request = {} + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_traffic_extensions(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_lb_traffic_extensions_rest_required_fields(request_type=dep.ListLbTrafficExtensionsRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_traffic_extensions._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_lb_traffic_extensions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ListLbTrafficExtensionsResponse() + # 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 = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_lb_traffic_extensions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_lb_traffic_extensions_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_lb_traffic_extensions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_lb_traffic_extensions_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_list_lb_traffic_extensions") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_list_lb_traffic_extensions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.ListLbTrafficExtensionsRequest.pb(dep.ListLbTrafficExtensionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = dep.ListLbTrafficExtensionsResponse.to_json(dep.ListLbTrafficExtensionsResponse()) + + request = dep.ListLbTrafficExtensionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ListLbTrafficExtensionsResponse() + + client.list_lb_traffic_extensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_lb_traffic_extensions_rest_bad_request(transport: str = 'rest', request_type=dep.ListLbTrafficExtensionsRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_lb_traffic_extensions(request) + + +def test_list_lb_traffic_extensions_rest_flattened(): + client = DepServiceClient( + 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 = dep.ListLbTrafficExtensionsResponse() + + # 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 = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_lb_traffic_extensions(**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/*}/lbTrafficExtensions" % client.transport._host, args[1]) + + +def test_list_lb_traffic_extensions_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent='parent_value', + ) + + +def test_list_lb_traffic_extensions_rest_pager(transport: str = 'rest'): + client = DepServiceClient( + 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 = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token='abc', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token='def', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dep.ListLbTrafficExtensionsResponse.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_lb_traffic_extensions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbTrafficExtension) + for i in results) + + pages = list(client.list_lb_traffic_extensions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + dep.GetLbTrafficExtensionRequest, + dict, +]) +def test_get_lb_traffic_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/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 = dep.LbTrafficExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + +def test_get_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + + request = {} + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.GetLbTrafficExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.LbTrafficExtension() + # 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 = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_lb_traffic_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_lb_traffic_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_lb_traffic_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_get_lb_traffic_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_get_lb_traffic_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.GetLbTrafficExtensionRequest.pb(dep.GetLbTrafficExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = dep.LbTrafficExtension.to_json(dep.LbTrafficExtension()) + + request = dep.GetLbTrafficExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.LbTrafficExtension() + + client.get_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.GetLbTrafficExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_lb_traffic_extension(request) + + +def test_get_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + 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 = dep.LbTrafficExtension() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/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 = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_lb_traffic_extension(**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/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) + + +def test_get_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name='name_value', + ) + + +def test_get_lb_traffic_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.CreateLbTrafficExtensionRequest, + dict, +]) +def test_create_lb_traffic_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["lb_traffic_extension"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} + # 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 = dep.CreateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] + + 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["lb_traffic_extension"].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["lb_traffic_extension"][field])): + del request_init["lb_traffic_extension"][field][i][subfield] + else: + del request_init["lb_traffic_extension"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + + request = {} + client.create_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.CreateLbTrafficExtensionRequest): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["lb_traffic_extension_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 "lbTrafficExtensionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_traffic_extension._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "lbTrafficExtensionId" in jsonified_request + assert jsonified_request["lbTrafficExtensionId"] == request_init["lb_traffic_extension_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["lbTrafficExtensionId"] = 'lb_traffic_extension_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_traffic_extension._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("lb_traffic_extension_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 "lbTrafficExtensionId" in jsonified_request + assert jsonified_request["lbTrafficExtensionId"] == 'lb_traffic_extension_id_value' + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_lb_traffic_extension(request) + + expected_params = [ + ( + "lbTrafficExtensionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_lb_traffic_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_lb_traffic_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("lbTrafficExtensionId", "requestId", )) & set(("parent", "lbTrafficExtensionId", "lbTrafficExtension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_create_lb_traffic_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_create_lb_traffic_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.CreateLbTrafficExtensionRequest.pb(dep.CreateLbTrafficExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.CreateLbTrafficExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.CreateLbTrafficExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_lb_traffic_extension(request) + + +def test_create_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + 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', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_lb_traffic_extension(**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/*}/lbTrafficExtensions" % client.transport._host, args[1]) + + +def test_create_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent='parent_value', + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + lb_traffic_extension_id='lb_traffic_extension_id_value', + ) + + +def test_create_lb_traffic_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.UpdateLbTrafficExtensionRequest, + dict, +]) +def test_update_lb_traffic_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} + request_init["lb_traffic_extension"] = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} + # 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 = dep.UpdateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] + + 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["lb_traffic_extension"].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["lb_traffic_extension"][field])): + del request_init["lb_traffic_extension"][field][i][subfield] + else: + del request_init["lb_traffic_extension"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + + request = {} + client.update_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.UpdateLbTrafficExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( + 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 + + response = client.update_lb_traffic_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_lb_traffic_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_lb_traffic_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("lbTrafficExtension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_update_lb_traffic_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_update_lb_traffic_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.UpdateLbTrafficExtensionRequest.pb(dep.UpdateLbTrafficExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.UpdateLbTrafficExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.UpdateLbTrafficExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_lb_traffic_extension(request) + + +def test_update_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + 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 = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + lb_traffic_extension=dep.LbTrafficExtension(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 + + client.update_lb_traffic_extension(**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/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) + + +def test_update_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_lb_traffic_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.DeleteLbTrafficExtensionRequest, + dict, +]) +def test_delete_lb_traffic_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_lb_traffic_extension_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 = DepServiceClient( + 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc + + request = {} + client.delete_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.DeleteLbTrafficExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_lb_traffic_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_lb_traffic_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_lb_traffic_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_delete_lb_traffic_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_delete_lb_traffic_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.DeleteLbTrafficExtensionRequest.pb(dep.DeleteLbTrafficExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.DeleteLbTrafficExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.DeleteLbTrafficExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_lb_traffic_extension(request) + + +def test_delete_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + 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/lbTrafficExtensions/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_lb_traffic_extension(**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/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) + + +def test_delete_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name='name_value', + ) + + +def test_delete_lb_traffic_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.ListLbRouteExtensionsRequest, + dict, +]) +def test_list_lb_route_extensions_rest(request_type): + client = DepServiceClient( + 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 = dep.ListLbRouteExtensionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_lb_route_extensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_lb_route_extensions_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 = DepServiceClient( + 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_lb_route_extensions 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_lb_route_extensions] = mock_rpc + + request = {} + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_route_extensions(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_lb_route_extensions_rest_required_fields(request_type=dep.ListLbRouteExtensionsRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_route_extensions._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_lb_route_extensions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ListLbRouteExtensionsResponse() + # 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 = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_lb_route_extensions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_lb_route_extensions_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_lb_route_extensions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_lb_route_extensions_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_list_lb_route_extensions") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_list_lb_route_extensions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.ListLbRouteExtensionsRequest.pb(dep.ListLbRouteExtensionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = dep.ListLbRouteExtensionsResponse.to_json(dep.ListLbRouteExtensionsResponse()) + + request = dep.ListLbRouteExtensionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ListLbRouteExtensionsResponse() + + client.list_lb_route_extensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_lb_route_extensions_rest_bad_request(transport: str = 'rest', request_type=dep.ListLbRouteExtensionsRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_lb_route_extensions(request) + + +def test_list_lb_route_extensions_rest_flattened(): + client = DepServiceClient( + 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 = dep.ListLbRouteExtensionsResponse() + + # 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 = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_lb_route_extensions(**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/*}/lbRouteExtensions" % client.transport._host, args[1]) + + +def test_list_lb_route_extensions_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent='parent_value', + ) + + +def test_list_lb_route_extensions_rest_pager(transport: str = 'rest'): + client = DepServiceClient( + 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 = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token='abc', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token='def', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token='ghi', + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dep.ListLbRouteExtensionsResponse.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_lb_route_extensions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbRouteExtension) + for i in results) + + pages = list(client.list_lb_route_extensions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + dep.GetLbRouteExtensionRequest, + dict, +]) +def test_get_lb_route_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/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 = dep.LbRouteExtension( + name='name_value', + description='description_value', + forwarding_rules=['forwarding_rules_value'], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_lb_route_extension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.forwarding_rules == ['forwarding_rules_value'] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + +def test_get_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + + request = {} + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.GetLbRouteExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.LbRouteExtension() + # 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 = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_lb_route_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_lb_route_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_lb_route_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_get_lb_route_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_get_lb_route_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.GetLbRouteExtensionRequest.pb(dep.GetLbRouteExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = dep.LbRouteExtension.to_json(dep.LbRouteExtension()) + + request = dep.GetLbRouteExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.LbRouteExtension() + + client.get_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.GetLbRouteExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_lb_route_extension(request) + + +def test_get_lb_route_extension_rest_flattened(): + client = DepServiceClient( + 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 = dep.LbRouteExtension() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/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 = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_lb_route_extension(**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/*/lbRouteExtensions/*}" % client.transport._host, args[1]) + + +def test_get_lb_route_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name='name_value', + ) + + +def test_get_lb_route_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.CreateLbRouteExtensionRequest, + dict, +]) +def test_create_lb_route_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["lb_route_extension"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} + # 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 = dep.CreateLbRouteExtensionRequest.meta.fields["lb_route_extension"] + + 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["lb_route_extension"].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["lb_route_extension"][field])): + del request_init["lb_route_extension"][field][i][subfield] + else: + del request_init["lb_route_extension"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_lb_route_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + + request = {} + client.create_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.CreateLbRouteExtensionRequest): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["lb_route_extension_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 "lbRouteExtensionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_route_extension._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "lbRouteExtensionId" in jsonified_request + assert jsonified_request["lbRouteExtensionId"] == request_init["lb_route_extension_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["lbRouteExtensionId"] = 'lb_route_extension_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_route_extension._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("lb_route_extension_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 "lbRouteExtensionId" in jsonified_request + assert jsonified_request["lbRouteExtensionId"] == 'lb_route_extension_id_value' + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_lb_route_extension(request) + + expected_params = [ + ( + "lbRouteExtensionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_lb_route_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_lb_route_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("lbRouteExtensionId", "requestId", )) & set(("parent", "lbRouteExtensionId", "lbRouteExtension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_create_lb_route_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_create_lb_route_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.CreateLbRouteExtensionRequest.pb(dep.CreateLbRouteExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.CreateLbRouteExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.CreateLbRouteExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_lb_route_extension(request) + + +def test_create_lb_route_extension_rest_flattened(): + client = DepServiceClient( + 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', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_lb_route_extension(**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/*}/lbRouteExtensions" % client.transport._host, args[1]) + + +def test_create_lb_route_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent='parent_value', + lb_route_extension=dep.LbRouteExtension(name='name_value'), + lb_route_extension_id='lb_route_extension_id_value', + ) + + +def test_create_lb_route_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.UpdateLbRouteExtensionRequest, + dict, +]) +def test_update_lb_route_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} + request_init["lb_route_extension"] = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} + # 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 = dep.UpdateLbRouteExtensionRequest.meta.fields["lb_route_extension"] + + 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["lb_route_extension"].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["lb_route_extension"][field])): + del request_init["lb_route_extension"][field][i][subfield] + else: + del request_init["lb_route_extension"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_lb_route_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + + request = {} + client.update_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.UpdateLbRouteExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( + 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 + + response = client.update_lb_route_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_lb_route_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_lb_route_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("lbRouteExtension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_update_lb_route_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_update_lb_route_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.UpdateLbRouteExtensionRequest.pb(dep.UpdateLbRouteExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.UpdateLbRouteExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.UpdateLbRouteExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_lb_route_extension(request) + + +def test_update_lb_route_extension_rest_flattened(): + client = DepServiceClient( + 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 = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + lb_route_extension=dep.LbRouteExtension(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 + + client.update_lb_route_extension(**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/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}" % client.transport._host, args[1]) + + +def test_update_lb_route_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_lb_route_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + dep.DeleteLbRouteExtensionRequest, + dict, +]) +def test_delete_lb_route_extension_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_lb_route_extension(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_lb_route_extension_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 = DepServiceClient( + 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_lb_route_extension 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_lb_route_extension] = mock_rpc + + request = {} + client.delete_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.DeleteLbRouteExtensionRequest): + transport_class = transports.DepServiceRestTransport + + 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_lb_route_extension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_lb_route_extension_rest_unset_required_fields(): + transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_lb_route_extension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(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.DepServiceRestInterceptor, "post_delete_lb_route_extension") as post, \ + mock.patch.object(transports.DepServiceRestInterceptor, "pre_delete_lb_route_extension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dep.DeleteLbRouteExtensionRequest.pb(dep.DeleteLbRouteExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = dep.DeleteLbRouteExtensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.DeleteLbRouteExtensionRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_lb_route_extension(request) + + +def test_delete_lb_route_extension_rest_flattened(): + client = DepServiceClient( + 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/lbRouteExtensions/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_lb_route_extension(**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/*/lbRouteExtensions/*}" % client.transport._host, args[1]) + + +def test_delete_lb_route_extension_rest_flattened_error(transport: str = 'rest'): + client = DepServiceClient( + 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_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name='name_value', + ) + + +def test_delete_lb_route_extension_rest_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DepServiceClient( + 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 = DepServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DepServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DepServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + transports.DepServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DepServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DepServiceGrpcTransport, + ) + +def test_dep_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DepServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dep_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_services_v1.services.dep_service.transports.DepServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DepServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_lb_traffic_extensions', + 'get_lb_traffic_extension', + 'create_lb_traffic_extension', + 'update_lb_traffic_extension', + 'delete_lb_traffic_extension', + 'list_lb_route_extensions', + 'get_lb_route_extension', + 'create_lb_route_extension', + 'update_lb_route_extension', + 'delete_lb_route_extension', + '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_dep_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_services_v1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DepServiceTransport( + 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_dep_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_services_v1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DepServiceTransport() + adc.assert_called_once() + + +def test_dep_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) + DepServiceClient() + 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.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + ], +) +def test_dep_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.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + transports.DepServiceRestTransport, + ], +) +def test_dep_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.DepServiceGrpcTransport, grpc_helpers), + (transports.DepServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dep_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( + "networkservices.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="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) +def test_dep_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_dep_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.DepServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dep_service_rest_lro_client(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dep_service_host_no_port(transport_name): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkservices.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dep_service_host_with_port(transport_name): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkservices.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkservices.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dep_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DepServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DepServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_lb_traffic_extensions._session + session2 = client2.transport.list_lb_traffic_extensions._session + assert session1 != session2 + session1 = client1.transport.get_lb_traffic_extension._session + session2 = client2.transport.get_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.create_lb_traffic_extension._session + session2 = client2.transport.create_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.update_lb_traffic_extension._session + session2 = client2.transport.update_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.delete_lb_traffic_extension._session + session2 = client2.transport.delete_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.list_lb_route_extensions._session + session2 = client2.transport.list_lb_route_extensions._session + assert session1 != session2 + session1 = client1.transport.get_lb_route_extension._session + session2 = client2.transport.get_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.create_lb_route_extension._session + session2 = client2.transport.create_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.update_lb_route_extension._session + session2 = client2.transport.update_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.delete_lb_route_extension._session + session2 = client2.transport.delete_lb_route_extension._session + assert session1 != session2 +def test_dep_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DepServiceGrpcTransport( + 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_dep_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DepServiceGrpcAsyncIOTransport( + 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.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) +def test_dep_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.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) +def test_dep_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_dep_service_grpc_lro_client(): + client = DepServiceClient( + 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_dep_service_grpc_lro_async_client(): + client = DepServiceAsyncClient( + 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_lb_route_extension_path(): + project = "squid" + location = "clam" + lb_route_extension = "whelk" + expected = "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format(project=project, location=location, lb_route_extension=lb_route_extension, ) + actual = DepServiceClient.lb_route_extension_path(project, location, lb_route_extension) + assert expected == actual + + +def test_parse_lb_route_extension_path(): + expected = { + "project": "octopus", + "location": "oyster", + "lb_route_extension": "nudibranch", + } + path = DepServiceClient.lb_route_extension_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_lb_route_extension_path(path) + assert expected == actual + +def test_lb_traffic_extension_path(): + project = "cuttlefish" + location = "mussel" + lb_traffic_extension = "winkle" + expected = "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format(project=project, location=location, lb_traffic_extension=lb_traffic_extension, ) + actual = DepServiceClient.lb_traffic_extension_path(project, location, lb_traffic_extension) + assert expected == actual + + +def test_parse_lb_traffic_extension_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "lb_traffic_extension": "abalone", + } + path = DepServiceClient.lb_traffic_extension_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_lb_traffic_extension_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DepServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DepServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DepServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DepServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DepServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DepServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DepServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DepServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DepServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DepServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.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.DepServiceTransport, '_prep_wrapped_messages') as prep: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DepServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DepServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DepServiceClient( + 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 = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DepServiceClient( + 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", [ + (DepServiceClient, transports.DepServiceGrpcTransport), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport), +]) +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-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py new file mode 100644 index 000000000000..a9c63c0e2a90 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py @@ -0,0 +1,31441 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from 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 + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_services_v1.services.network_services import NetworkServicesAsyncClient +from google.cloud.network_services_v1.services.network_services import NetworkServicesClient +from google.cloud.network_services_v1.services.network_services import pagers +from google.cloud.network_services_v1.services.network_services import transports +from google.cloud.network_services_v1.types import common +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import service_binding as gcn_service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# 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 NetworkServicesClient._get_default_mtls_endpoint(None) is None + assert NetworkServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert NetworkServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert NetworkServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert NetworkServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert NetworkServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NetworkServicesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + NetworkServicesClient._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 NetworkServicesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NetworkServicesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkServicesClient._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 NetworkServicesClient._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 NetworkServicesClient._get_client_cert_source(None, False) is None + assert NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert NetworkServicesClient._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 NetworkServicesClient._get_client_cert_source(None, True) is mock_default_cert_source + assert NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) +@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NetworkServicesClient._DEFAULT_UNIVERSE + default_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert NetworkServicesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert NetworkServicesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "always") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + assert NetworkServicesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + assert NetworkServicesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkServicesClient._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 NetworkServicesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert NetworkServicesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert NetworkServicesClient._get_universe_domain(None, None) == NetworkServicesClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + NetworkServicesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkServicesClient, "grpc"), + (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), +]) +def test_network_services_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 == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkservices.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.NetworkServicesGrpcTransport, "grpc"), + (transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkServicesRestTransport, "rest"), +]) +def test_network_services_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", [ + (NetworkServicesClient, "grpc"), + (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), +]) +def test_network_services_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 == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networkservices.googleapis.com' + ) + + +def test_network_services_client_get_transport_class(): + transport = NetworkServicesClient.get_transport_class() + available_transports = [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesRestTransport, + ] + assert transport in available_transports + + transport = NetworkServicesClient.get_transport_class("grpc") + assert transport == transports.NetworkServicesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), +]) +@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) +@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) +def test_network_services_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(NetworkServicesClient, '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(NetworkServicesClient, '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", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", "true"), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", "false"), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", "true"), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", "false"), +]) +@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) +@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_network_services_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", [ + NetworkServicesClient, NetworkServicesAsyncClient +]) +@mock.patch.object(NetworkServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkServicesClient)) +@mock.patch.object(NetworkServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkServicesAsyncClient)) +def test_network_services_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", [ + NetworkServicesClient, NetworkServicesAsyncClient +]) +@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) +@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) +def test_network_services_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NetworkServicesClient._DEFAULT_UNIVERSE + default_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkServicesClient._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", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), +]) +def test_network_services_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", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", grpc_helpers), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", None), +]) +def test_network_services_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_services_client_client_options_from_dict(): + with mock.patch('google.cloud.network_services_v1.services.network_services.transports.NetworkServicesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = NetworkServicesClient( + 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", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", grpc_helpers), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_network_services_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( + "networkservices.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="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + endpoint_policy.ListEndpointPoliciesRequest, + dict, +]) +def test_list_endpoint_policies(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_endpoint_policies_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_endpoint_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.ListEndpointPoliciesRequest() + + +def test_list_endpoint_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 = NetworkServicesClient( + 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 = endpoint_policy.ListEndpointPoliciesRequest( + 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_endpoint_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_endpoint_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.ListEndpointPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policies] = mock_rpc + request = {} + client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_endpoint_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_endpoint_policies_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_endpoint_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.ListEndpointPoliciesRequest() + +@pytest.mark.asyncio +async def test_list_endpoint_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_endpoint_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_endpoint_policies] = mock_object + + request = {} + await client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_endpoint_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.ListEndpointPoliciesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async_from_dict(): + await test_list_endpoint_policies_async(request_type=dict) + + +def test_list_endpoint_policies_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.ListEndpointPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + client.list_endpoint_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_endpoint_policies_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.ListEndpointPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse()) + await client.list_endpoint_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_endpoint_policies_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoint_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_endpoint_policies_flattened_error(): + client = NetworkServicesClient( + 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_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_endpoint_policies_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoint_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_endpoint_policies_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_endpoint_policies_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_endpoint_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token='abc', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token='def', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token='ghi', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_endpoint_policies(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) + for i in results) +def test_list_endpoint_policies_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_endpoint_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token='abc', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token='def', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token='ghi', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_endpoint_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_endpoint_policies_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token='abc', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token='def', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token='ghi', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_endpoint_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, endpoint_policy.EndpointPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token='abc', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token='def', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token='ghi', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + 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_endpoint_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", [ + endpoint_policy.GetEndpointPolicyRequest, + dict, +]) +def test_get_endpoint_policy(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy( + name='name_value', + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy='authorization_policy_value', + description='description_value', + server_tls_policy='server_tls_policy_value', + client_tls_policy='client_tls_policy_value', + ) + response = client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == 'name_value' + assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + assert response.authorization_policy == 'authorization_policy_value' + assert response.description == 'description_value' + assert response.server_tls_policy == 'server_tls_policy_value' + assert response.client_tls_policy == 'client_tls_policy_value' + + +def test_get_endpoint_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.GetEndpointPolicyRequest() + + +def test_get_endpoint_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 = NetworkServicesClient( + 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 = endpoint_policy.GetEndpointPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.GetEndpointPolicyRequest( + name='name_value', + ) + +def test_get_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + request = {} + client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_endpoint_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_endpoint_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy( + name='name_value', + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy='authorization_policy_value', + description='description_value', + server_tls_policy='server_tls_policy_value', + client_tls_policy='client_tls_policy_value', + )) + response = await client.get_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.GetEndpointPolicyRequest() + +@pytest.mark.asyncio +async def test_get_endpoint_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_endpoint_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_endpoint_policy] = mock_object + + request = {} + await client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.GetEndpointPolicyRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy( + name='name_value', + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy='authorization_policy_value', + description='description_value', + server_tls_policy='server_tls_policy_value', + client_tls_policy='client_tls_policy_value', + )) + response = await client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == 'name_value' + assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + assert response.authorization_policy == 'authorization_policy_value' + assert response.description == 'description_value' + assert response.server_tls_policy == 'server_tls_policy_value' + assert response.client_tls_policy == 'client_tls_policy_value' + + +@pytest.mark.asyncio +async def test_get_endpoint_policy_async_from_dict(): + await test_get_endpoint_policy_async(request_type=dict) + + +def test_get_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.GetEndpointPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + call.return_value = endpoint_policy.EndpointPolicy() + client.get_endpoint_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_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.GetEndpointPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy()) + await client.get_endpoint_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_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint_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_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint_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_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_endpoint_policy.CreateEndpointPolicyRequest, + dict, +]) +def test_create_endpoint_policy(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_endpoint_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest() + + +def test_create_endpoint_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 = NetworkServicesClient( + 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_endpoint_policy.CreateEndpointPolicyRequest( + parent='parent_value', + endpoint_policy_id='endpoint_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest( + parent='parent_value', + endpoint_policy_id='endpoint_policy_id_value', + ) + +def test_create_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + request = {} + client.create_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_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_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest() + +@pytest.mark.asyncio +async def test_create_endpoint_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_endpoint_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_endpoint_policy] = mock_object + + request = {} + await client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + 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_endpoint_policy_async_from_dict(): + await test_create_endpoint_policy_async(request_type=dict) + + +def test_create_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_endpoint_policy.CreateEndpointPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_endpoint_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_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_endpoint_policy.CreateEndpointPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_endpoint_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_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_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_endpoint_policy( + parent='parent_value', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_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].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name='name_value') + assert arg == mock_val + arg = args[0].endpoint_policy_id + mock_val = 'endpoint_policy_id_value' + assert arg == mock_val + + +def test_create_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent='parent_value', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_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_endpoint_policy( + parent='parent_value', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_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].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name='name_value') + assert arg == mock_val + arg = args[0].endpoint_policy_id + mock_val = 'endpoint_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent='parent_value', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, + dict, +]) +def test_update_endpoint_policy(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_endpoint_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest() + + +def test_update_endpoint_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 = NetworkServicesClient( + 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_endpoint_policy.UpdateEndpointPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest( + ) + +def test_update_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + request = {} + client.update_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_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_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest() + +@pytest.mark.asyncio +async def test_update_endpoint_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_endpoint_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_endpoint_policy] = mock_object + + request = {} + await client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + 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_endpoint_policy_async_from_dict(): + await test_update_endpoint_policy_async(request_type=dict) + + +def test_update_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_endpoint_policy.UpdateEndpointPolicyRequest() + + request.endpoint_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_endpoint_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', + 'endpoint_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_endpoint_policy.UpdateEndpointPolicyRequest() + + request.endpoint_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_endpoint_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', + 'endpoint_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_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_endpoint_policy( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(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_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_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_endpoint_policy( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(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_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + endpoint_policy.DeleteEndpointPolicyRequest, + dict, +]) +def test_delete_endpoint_policy(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_endpoint_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest() + + +def test_delete_endpoint_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 = NetworkServicesClient( + 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 = endpoint_policy.DeleteEndpointPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest( + name='name_value', + ) + +def test_delete_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + request = {} + client.delete_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_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_endpoint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest() + +@pytest.mark.asyncio +async def test_delete_endpoint_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_endpoint_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_endpoint_policy] = mock_object + + request = {} + await client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.DeleteEndpointPolicyRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.DeleteEndpointPolicyRequest() + 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_endpoint_policy_async_from_dict(): + await test_delete_endpoint_policy_async(request_type=dict) + + +def test_delete_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.DeleteEndpointPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_endpoint_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_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.DeleteEndpointPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_endpoint_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_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_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_endpoint_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_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_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_endpoint_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_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gateway.ListGatewaysRequest, + dict, +]) +def test_list_gateways(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateways), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.ListGatewaysResponse( + next_page_token='next_page_token_value', + ) + response = client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gateway.ListGatewaysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGatewaysPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_gateways_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_gateways() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.ListGatewaysRequest() + + +def test_list_gateways_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 = NetworkServicesClient( + 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 = gateway.ListGatewaysRequest( + 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_gateways), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_gateways(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.ListGatewaysRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_gateways_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 = NetworkServicesClient( + 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_gateways 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_gateways] = mock_rpc + request = {} + client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gateways(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_gateways_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_gateways() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.ListGatewaysRequest() + +@pytest.mark.asyncio +async def test_list_gateways_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_gateways in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_gateways] = mock_object + + request = {} + await client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_gateways(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_gateways_async(transport: str = 'grpc_asyncio', request_type=gateway.ListGatewaysRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateways), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gateway.ListGatewaysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGatewaysAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_gateways_async_from_dict(): + await test_list_gateways_async(request_type=dict) + + +def test_list_gateways_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.ListGatewaysRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + call.return_value = gateway.ListGatewaysResponse() + client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_gateways_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.ListGatewaysRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse()) + await client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_gateways_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.ListGatewaysResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_gateways( + 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_gateways_flattened_error(): + client = NetworkServicesClient( + 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_gateways( + gateway.ListGatewaysRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_gateways_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.ListGatewaysResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_gateways( + 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_gateways_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_gateways( + gateway.ListGatewaysRequest(), + parent='parent_value', + ) + + +def test_list_gateways_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_gateways), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token='abc', + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token='def', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token='ghi', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_gateways(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gateway.Gateway) + for i in results) +def test_list_gateways_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_gateways), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token='abc', + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token='def', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token='ghi', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + RuntimeError, + ) + pages = list(client.list_gateways(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_gateways_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token='abc', + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token='def', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token='ghi', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_gateways(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, gateway.Gateway) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_gateways_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gateways), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token='abc', + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token='def', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token='ghi', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + 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_gateways(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", [ + gateway.GetGatewayRequest, + dict, +]) +def test_get_gateway(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.Gateway( + name='name_value', + self_link='self_link_value', + description='description_value', + type_=gateway.Gateway.Type.OPEN_MESH, + ports=[568], + scope='scope_value', + server_tls_policy='server_tls_policy_value', + ) + response = client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gateway.GetGatewayRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gateway.Gateway) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.type_ == gateway.Gateway.Type.OPEN_MESH + assert response.ports == [568] + assert response.scope == 'scope_value' + assert response.server_tls_policy == 'server_tls_policy_value' + + +def test_get_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.GetGatewayRequest() + + +def test_get_gateway_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 = NetworkServicesClient( + 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 = gateway.GetGatewayRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_gateway(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.GetGatewayRequest( + name='name_value', + ) + +def test_get_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + request = {} + client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_gateway(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_gateway_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway( + name='name_value', + self_link='self_link_value', + description='description_value', + type_=gateway.Gateway.Type.OPEN_MESH, + ports=[568], + scope='scope_value', + server_tls_policy='server_tls_policy_value', + )) + response = await client.get_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.GetGatewayRequest() + +@pytest.mark.asyncio +async def test_get_gateway_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_gateway in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_gateway] = mock_object + + request = {} + await client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_gateway(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_gateway_async(transport: str = 'grpc_asyncio', request_type=gateway.GetGatewayRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway( + name='name_value', + self_link='self_link_value', + description='description_value', + type_=gateway.Gateway.Type.OPEN_MESH, + ports=[568], + scope='scope_value', + server_tls_policy='server_tls_policy_value', + )) + response = await client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gateway.GetGatewayRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gateway.Gateway) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.type_ == gateway.Gateway.Type.OPEN_MESH + assert response.ports == [568] + assert response.scope == 'scope_value' + assert response.server_tls_policy == 'server_tls_policy_value' + + +@pytest.mark.asyncio +async def test_get_gateway_async_from_dict(): + await test_get_gateway_async(request_type=dict) + + +def test_get_gateway_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.GetGatewayRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + call.return_value = gateway.Gateway() + client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_gateway_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.GetGatewayRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway()) + await client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_gateway_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.Gateway() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_gateway( + 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_gateway_flattened_error(): + client = NetworkServicesClient( + 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_gateway( + gateway.GetGatewayRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_gateway_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gateway.Gateway() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_gateway( + 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_gateway_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_gateway( + gateway.GetGatewayRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_gateway.CreateGatewayRequest, + dict, +]) +def test_create_gateway(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_gateway.CreateGatewayRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.CreateGatewayRequest() + + +def test_create_gateway_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 = NetworkServicesClient( + 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_gateway.CreateGatewayRequest( + parent='parent_value', + gateway_id='gateway_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_gateway(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.CreateGatewayRequest( + parent='parent_value', + gateway_id='gateway_id_value', + ) + +def test_create_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + request = {} + client.create_gateway(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_gateway(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_gateway_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__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_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.CreateGatewayRequest() + +@pytest.mark.asyncio +async def test_create_gateway_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_gateway in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_gateway] = mock_object + + request = {} + await client.create_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_gateway(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_gateway_async(transport: str = 'grpc_asyncio', request_type=gcn_gateway.CreateGatewayRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__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_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_gateway.CreateGatewayRequest() + 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_gateway_async_from_dict(): + await test_create_gateway_async(request_type=dict) + + +def test_create_gateway_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_gateway.CreateGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_gateway_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_gateway.CreateGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_gateway_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__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_gateway( + parent='parent_value', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_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].gateway + mock_val = gcn_gateway.Gateway(name='name_value') + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + + +def test_create_gateway_flattened_error(): + client = NetworkServicesClient( + 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_gateway( + gcn_gateway.CreateGatewayRequest(), + parent='parent_value', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_id_value', + ) + +@pytest.mark.asyncio +async def test_create_gateway_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_gateway), + '__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_gateway( + parent='parent_value', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_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].gateway + mock_val = gcn_gateway.Gateway(name='name_value') + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_gateway_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_gateway( + gcn_gateway.CreateGatewayRequest(), + parent='parent_value', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_gateway.UpdateGatewayRequest, + dict, +]) +def test_update_gateway(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_gateway.UpdateGatewayRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.UpdateGatewayRequest() + + +def test_update_gateway_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 = NetworkServicesClient( + 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_gateway.UpdateGatewayRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_gateway(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.UpdateGatewayRequest( + ) + +def test_update_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + request = {} + client.update_gateway(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_gateway(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_gateway_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__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_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_gateway.UpdateGatewayRequest() + +@pytest.mark.asyncio +async def test_update_gateway_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_gateway in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_gateway] = mock_object + + request = {} + await client.update_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_gateway(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_gateway_async(transport: str = 'grpc_asyncio', request_type=gcn_gateway.UpdateGatewayRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__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_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_gateway.UpdateGatewayRequest() + 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_gateway_async_from_dict(): + await test_update_gateway_async(request_type=dict) + + +def test_update_gateway_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_gateway.UpdateGatewayRequest() + + request.gateway.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'gateway.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_gateway_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_gateway.UpdateGatewayRequest() + + request.gateway.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'gateway.name=name_value', + ) in kw['metadata'] + + +def test_update_gateway_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__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_gateway( + gateway=gcn_gateway.Gateway(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].gateway + mock_val = gcn_gateway.Gateway(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_gateway_flattened_error(): + client = NetworkServicesClient( + 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_gateway( + gcn_gateway.UpdateGatewayRequest(), + gateway=gcn_gateway.Gateway(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_gateway_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_gateway), + '__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_gateway( + gateway=gcn_gateway.Gateway(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].gateway + mock_val = gcn_gateway.Gateway(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_gateway_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_gateway( + gcn_gateway.UpdateGatewayRequest(), + gateway=gcn_gateway.Gateway(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + gateway.DeleteGatewayRequest, + dict, +]) +def test_delete_gateway(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gateway.DeleteGatewayRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.DeleteGatewayRequest() + + +def test_delete_gateway_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 = NetworkServicesClient( + 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 = gateway.DeleteGatewayRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_gateway(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.DeleteGatewayRequest( + name='name_value', + ) + +def test_delete_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + request = {} + client.delete_gateway(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_gateway(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_gateway_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__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_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gateway.DeleteGatewayRequest() + +@pytest.mark.asyncio +async def test_delete_gateway_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_gateway in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_gateway] = mock_object + + request = {} + await client.delete_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_gateway(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_gateway_async(transport: str = 'grpc_asyncio', request_type=gateway.DeleteGatewayRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_gateway), + '__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_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gateway.DeleteGatewayRequest() + 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_gateway_async_from_dict(): + await test_delete_gateway_async(request_type=dict) + + +def test_delete_gateway_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.DeleteGatewayRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_gateway_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gateway.DeleteGatewayRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_gateway_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__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_gateway( + 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_gateway_flattened_error(): + client = NetworkServicesClient( + 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_gateway( + gateway.DeleteGatewayRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_gateway_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_gateway), + '__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_gateway( + 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_gateway_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_gateway( + gateway.DeleteGatewayRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + grpc_route.ListGrpcRoutesRequest, + dict, +]) +def test_list_grpc_routes(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.ListGrpcRoutesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grpc_route.ListGrpcRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGrpcRoutesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_grpc_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_grpc_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.ListGrpcRoutesRequest() + + +def test_list_grpc_routes_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 = NetworkServicesClient( + 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 = grpc_route.ListGrpcRoutesRequest( + 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_grpc_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_grpc_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.ListGrpcRoutesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_grpc_routes_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 = NetworkServicesClient( + 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_grpc_routes 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_grpc_routes] = mock_rpc + request = {} + client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_grpc_routes(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_grpc_routes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_grpc_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.ListGrpcRoutesRequest() + +@pytest.mark.asyncio +async def test_list_grpc_routes_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_grpc_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_grpc_routes] = mock_object + + request = {} + await client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_grpc_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_grpc_routes_async(transport: str = 'grpc_asyncio', request_type=grpc_route.ListGrpcRoutesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grpc_route.ListGrpcRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGrpcRoutesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_grpc_routes_async_from_dict(): + await test_list_grpc_routes_async(request_type=dict) + + +def test_list_grpc_routes_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.ListGrpcRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + call.return_value = grpc_route.ListGrpcRoutesResponse() + client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_grpc_routes_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.ListGrpcRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse()) + await client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_grpc_routes_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.ListGrpcRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_grpc_routes( + 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_grpc_routes_flattened_error(): + client = NetworkServicesClient( + 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_grpc_routes( + grpc_route.ListGrpcRoutesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_grpc_routes_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.ListGrpcRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_grpc_routes( + 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_grpc_routes_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_grpc_routes( + grpc_route.ListGrpcRoutesRequest(), + parent='parent_value', + ) + + +def test_list_grpc_routes_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_grpc_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token='abc', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token='def', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token='ghi', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_grpc_routes(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grpc_route.GrpcRoute) + for i in results) +def test_list_grpc_routes_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_grpc_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token='abc', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token='def', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token='ghi', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + RuntimeError, + ) + pages = list(client.list_grpc_routes(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_grpc_routes_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token='abc', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token='def', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token='ghi', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_grpc_routes(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, grpc_route.GrpcRoute) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_grpc_routes_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_grpc_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token='abc', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token='def', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token='ghi', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + 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_grpc_routes(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", [ + grpc_route.GetGrpcRouteRequest, + dict, +]) +def test_get_grpc_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.GrpcRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + response = client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grpc_route.GetGrpcRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grpc_route.GrpcRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +def test_get_grpc_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.GetGrpcRouteRequest() + + +def test_get_grpc_route_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 = NetworkServicesClient( + 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 = grpc_route.GetGrpcRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_grpc_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.GetGrpcRouteRequest( + name='name_value', + ) + +def test_get_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + request = {} + client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_grpc_route(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_grpc_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.GetGrpcRouteRequest() + +@pytest.mark.asyncio +async def test_get_grpc_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_grpc_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_grpc_route] = mock_object + + request = {} + await client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_grpc_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_grpc_route_async(transport: str = 'grpc_asyncio', request_type=grpc_route.GetGrpcRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grpc_route.GetGrpcRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grpc_route.GrpcRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +@pytest.mark.asyncio +async def test_get_grpc_route_async_from_dict(): + await test_get_grpc_route_async(request_type=dict) + + +def test_get_grpc_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.GetGrpcRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + call.return_value = grpc_route.GrpcRoute() + client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_grpc_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.GetGrpcRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute()) + await client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_grpc_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.GrpcRoute() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_grpc_route( + 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_grpc_route_flattened_error(): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.GetGrpcRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_grpc_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_route.GrpcRoute() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_grpc_route( + 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_grpc_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_grpc_route( + grpc_route.GetGrpcRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_grpc_route.CreateGrpcRouteRequest, + dict, +]) +def test_create_grpc_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_grpc_route.CreateGrpcRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_grpc_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest() + + +def test_create_grpc_route_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 = NetworkServicesClient( + 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_grpc_route.CreateGrpcRouteRequest( + parent='parent_value', + grpc_route_id='grpc_route_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_grpc_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest( + parent='parent_value', + grpc_route_id='grpc_route_id_value', + ) + +def test_create_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + request = {} + client.create_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__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_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest() + +@pytest.mark.asyncio +async def test_create_grpc_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_grpc_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_grpc_route] = mock_object + + request = {} + await client.create_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_grpc_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_grpc_route_async(transport: str = 'grpc_asyncio', request_type=gcn_grpc_route.CreateGrpcRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__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_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_grpc_route.CreateGrpcRouteRequest() + 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_grpc_route_async_from_dict(): + await test_create_grpc_route_async(request_type=dict) + + +def test_create_grpc_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_grpc_route.CreateGrpcRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_grpc_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_grpc_route.CreateGrpcRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_grpc_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__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_grpc_route( + parent='parent_value', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_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].grpc_route + mock_val = gcn_grpc_route.GrpcRoute(name='name_value') + assert arg == mock_val + arg = args[0].grpc_route_id + mock_val = 'grpc_route_id_value' + assert arg == mock_val + + +def test_create_grpc_route_flattened_error(): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.CreateGrpcRouteRequest(), + parent='parent_value', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_id_value', + ) + +@pytest.mark.asyncio +async def test_create_grpc_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_grpc_route), + '__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_grpc_route( + parent='parent_value', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_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].grpc_route + mock_val = gcn_grpc_route.GrpcRoute(name='name_value') + assert arg == mock_val + arg = args[0].grpc_route_id + mock_val = 'grpc_route_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_grpc_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_grpc_route( + gcn_grpc_route.CreateGrpcRouteRequest(), + parent='parent_value', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_grpc_route.UpdateGrpcRouteRequest, + dict, +]) +def test_update_grpc_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_grpc_route.UpdateGrpcRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_grpc_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest() + + +def test_update_grpc_route_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 = NetworkServicesClient( + 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_grpc_route.UpdateGrpcRouteRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_grpc_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest( + ) + +def test_update_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + request = {} + client.update_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__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_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest() + +@pytest.mark.asyncio +async def test_update_grpc_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_grpc_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_grpc_route] = mock_object + + request = {} + await client.update_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_grpc_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_grpc_route_async(transport: str = 'grpc_asyncio', request_type=gcn_grpc_route.UpdateGrpcRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__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_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_grpc_route.UpdateGrpcRouteRequest() + 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_grpc_route_async_from_dict(): + await test_update_grpc_route_async(request_type=dict) + + +def test_update_grpc_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_grpc_route.UpdateGrpcRouteRequest() + + request.grpc_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'grpc_route.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_grpc_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_grpc_route.UpdateGrpcRouteRequest() + + request.grpc_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'grpc_route.name=name_value', + ) in kw['metadata'] + + +def test_update_grpc_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__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_grpc_route( + grpc_route=gcn_grpc_route.GrpcRoute(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].grpc_route + mock_val = gcn_grpc_route.GrpcRoute(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_grpc_route_flattened_error(): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.UpdateGrpcRouteRequest(), + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_grpc_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_grpc_route), + '__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_grpc_route( + grpc_route=gcn_grpc_route.GrpcRoute(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].grpc_route + mock_val = gcn_grpc_route.GrpcRoute(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_grpc_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_grpc_route( + gcn_grpc_route.UpdateGrpcRouteRequest(), + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + grpc_route.DeleteGrpcRouteRequest, + dict, +]) +def test_delete_grpc_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grpc_route.DeleteGrpcRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_grpc_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.DeleteGrpcRouteRequest() + + +def test_delete_grpc_route_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 = NetworkServicesClient( + 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 = grpc_route.DeleteGrpcRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_grpc_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.DeleteGrpcRouteRequest( + name='name_value', + ) + +def test_delete_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + request = {} + client.delete_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__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_grpc_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grpc_route.DeleteGrpcRouteRequest() + +@pytest.mark.asyncio +async def test_delete_grpc_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_grpc_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_grpc_route] = mock_object + + request = {} + await client.delete_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_grpc_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_grpc_route_async(transport: str = 'grpc_asyncio', request_type=grpc_route.DeleteGrpcRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_grpc_route), + '__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_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grpc_route.DeleteGrpcRouteRequest() + 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_grpc_route_async_from_dict(): + await test_delete_grpc_route_async(request_type=dict) + + +def test_delete_grpc_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.DeleteGrpcRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_grpc_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grpc_route.DeleteGrpcRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_grpc_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__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_grpc_route( + 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_grpc_route_flattened_error(): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.DeleteGrpcRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_grpc_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_grpc_route), + '__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_grpc_route( + 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_grpc_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_grpc_route( + grpc_route.DeleteGrpcRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + http_route.ListHttpRoutesRequest, + dict, +]) +def test_list_http_routes(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.ListHttpRoutesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = http_route.ListHttpRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHttpRoutesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_http_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_http_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.ListHttpRoutesRequest() + + +def test_list_http_routes_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 = NetworkServicesClient( + 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 = http_route.ListHttpRoutesRequest( + 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_http_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_http_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.ListHttpRoutesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_http_routes_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 = NetworkServicesClient( + 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_http_routes 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_http_routes] = mock_rpc + request = {} + client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_http_routes(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_http_routes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_http_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.ListHttpRoutesRequest() + +@pytest.mark.asyncio +async def test_list_http_routes_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_http_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_http_routes] = mock_object + + request = {} + await client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_http_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_http_routes_async(transport: str = 'grpc_asyncio', request_type=http_route.ListHttpRoutesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = http_route.ListHttpRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHttpRoutesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_http_routes_async_from_dict(): + await test_list_http_routes_async(request_type=dict) + + +def test_list_http_routes_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.ListHttpRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + call.return_value = http_route.ListHttpRoutesResponse() + client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_http_routes_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.ListHttpRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse()) + await client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_http_routes_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.ListHttpRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_http_routes( + 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_http_routes_flattened_error(): + client = NetworkServicesClient( + 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_http_routes( + http_route.ListHttpRoutesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_http_routes_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.ListHttpRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_http_routes( + 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_http_routes_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_http_routes( + http_route.ListHttpRoutesRequest(), + parent='parent_value', + ) + + +def test_list_http_routes_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_http_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token='abc', + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token='def', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token='ghi', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_http_routes(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, http_route.HttpRoute) + for i in results) +def test_list_http_routes_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_http_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token='abc', + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token='def', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token='ghi', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + RuntimeError, + ) + pages = list(client.list_http_routes(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_http_routes_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token='abc', + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token='def', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token='ghi', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_http_routes(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, http_route.HttpRoute) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_http_routes_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_http_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token='abc', + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token='def', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token='ghi', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + 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_http_routes(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", [ + http_route.GetHttpRouteRequest, + dict, +]) +def test_get_http_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.HttpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + response = client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = http_route.GetHttpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, http_route.HttpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +def test_get_http_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.GetHttpRouteRequest() + + +def test_get_http_route_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 = NetworkServicesClient( + 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 = http_route.GetHttpRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_http_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.GetHttpRouteRequest( + name='name_value', + ) + +def test_get_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + request = {} + client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_http_route(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_http_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.GetHttpRouteRequest() + +@pytest.mark.asyncio +async def test_get_http_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_http_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_http_route] = mock_object + + request = {} + await client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_http_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_http_route_async(transport: str = 'grpc_asyncio', request_type=http_route.GetHttpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = http_route.GetHttpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, http_route.HttpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +@pytest.mark.asyncio +async def test_get_http_route_async_from_dict(): + await test_get_http_route_async(request_type=dict) + + +def test_get_http_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.GetHttpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + call.return_value = http_route.HttpRoute() + client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_http_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.GetHttpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute()) + await client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_http_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.HttpRoute() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_http_route( + 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_http_route_flattened_error(): + client = NetworkServicesClient( + 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_http_route( + http_route.GetHttpRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_http_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = http_route.HttpRoute() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_http_route( + 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_http_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_http_route( + http_route.GetHttpRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_http_route.CreateHttpRouteRequest, + dict, +]) +def test_create_http_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_http_route.CreateHttpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_http_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.CreateHttpRouteRequest() + + +def test_create_http_route_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 = NetworkServicesClient( + 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_http_route.CreateHttpRouteRequest( + parent='parent_value', + http_route_id='http_route_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_http_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.CreateHttpRouteRequest( + parent='parent_value', + http_route_id='http_route_id_value', + ) + +def test_create_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + request = {} + client.create_http_route(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_http_route(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_http_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__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_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.CreateHttpRouteRequest() + +@pytest.mark.asyncio +async def test_create_http_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_http_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_http_route] = mock_object + + request = {} + await client.create_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_http_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_http_route_async(transport: str = 'grpc_asyncio', request_type=gcn_http_route.CreateHttpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__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_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_http_route.CreateHttpRouteRequest() + 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_http_route_async_from_dict(): + await test_create_http_route_async(request_type=dict) + + +def test_create_http_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_http_route.CreateHttpRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_http_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_http_route.CreateHttpRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_http_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__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_http_route( + parent='parent_value', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_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].http_route + mock_val = gcn_http_route.HttpRoute(name='name_value') + assert arg == mock_val + arg = args[0].http_route_id + mock_val = 'http_route_id_value' + assert arg == mock_val + + +def test_create_http_route_flattened_error(): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.CreateHttpRouteRequest(), + parent='parent_value', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_id_value', + ) + +@pytest.mark.asyncio +async def test_create_http_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_http_route), + '__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_http_route( + parent='parent_value', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_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].http_route + mock_val = gcn_http_route.HttpRoute(name='name_value') + assert arg == mock_val + arg = args[0].http_route_id + mock_val = 'http_route_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_http_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_http_route( + gcn_http_route.CreateHttpRouteRequest(), + parent='parent_value', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_http_route.UpdateHttpRouteRequest, + dict, +]) +def test_update_http_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_http_route.UpdateHttpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_http_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.UpdateHttpRouteRequest() + + +def test_update_http_route_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 = NetworkServicesClient( + 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_http_route.UpdateHttpRouteRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_http_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.UpdateHttpRouteRequest( + ) + +def test_update_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + request = {} + client.update_http_route(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_http_route(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_http_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__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_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_http_route.UpdateHttpRouteRequest() + +@pytest.mark.asyncio +async def test_update_http_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_http_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_http_route] = mock_object + + request = {} + await client.update_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_http_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_http_route_async(transport: str = 'grpc_asyncio', request_type=gcn_http_route.UpdateHttpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__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_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_http_route.UpdateHttpRouteRequest() + 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_http_route_async_from_dict(): + await test_update_http_route_async(request_type=dict) + + +def test_update_http_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_http_route.UpdateHttpRouteRequest() + + request.http_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'http_route.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_http_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_http_route.UpdateHttpRouteRequest() + + request.http_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'http_route.name=name_value', + ) in kw['metadata'] + + +def test_update_http_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__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_http_route( + http_route=gcn_http_route.HttpRoute(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].http_route + mock_val = gcn_http_route.HttpRoute(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_http_route_flattened_error(): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.UpdateHttpRouteRequest(), + http_route=gcn_http_route.HttpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_http_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_http_route), + '__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_http_route( + http_route=gcn_http_route.HttpRoute(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].http_route + mock_val = gcn_http_route.HttpRoute(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_http_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_http_route( + gcn_http_route.UpdateHttpRouteRequest(), + http_route=gcn_http_route.HttpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + http_route.DeleteHttpRouteRequest, + dict, +]) +def test_delete_http_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = http_route.DeleteHttpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_http_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.DeleteHttpRouteRequest() + + +def test_delete_http_route_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 = NetworkServicesClient( + 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 = http_route.DeleteHttpRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_http_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.DeleteHttpRouteRequest( + name='name_value', + ) + +def test_delete_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + request = {} + client.delete_http_route(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_http_route(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_http_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__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_http_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == http_route.DeleteHttpRouteRequest() + +@pytest.mark.asyncio +async def test_delete_http_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_http_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_http_route] = mock_object + + request = {} + await client.delete_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_http_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_http_route_async(transport: str = 'grpc_asyncio', request_type=http_route.DeleteHttpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_http_route), + '__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_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = http_route.DeleteHttpRouteRequest() + 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_http_route_async_from_dict(): + await test_delete_http_route_async(request_type=dict) + + +def test_delete_http_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.DeleteHttpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_http_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = http_route.DeleteHttpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_http_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__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_http_route( + 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_http_route_flattened_error(): + client = NetworkServicesClient( + 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_http_route( + http_route.DeleteHttpRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_http_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_http_route), + '__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_http_route( + 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_http_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_http_route( + http_route.DeleteHttpRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + tcp_route.ListTcpRoutesRequest, + dict, +]) +def test_list_tcp_routes(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.ListTcpRoutesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tcp_route.ListTcpRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTcpRoutesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tcp_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_tcp_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.ListTcpRoutesRequest() + + +def test_list_tcp_routes_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 = NetworkServicesClient( + 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 = tcp_route.ListTcpRoutesRequest( + 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_tcp_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_tcp_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.ListTcpRoutesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_tcp_routes_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 = NetworkServicesClient( + 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_tcp_routes 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_tcp_routes] = mock_rpc + request = {} + client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tcp_routes(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_tcp_routes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tcp_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.ListTcpRoutesRequest() + +@pytest.mark.asyncio +async def test_list_tcp_routes_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tcp_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_tcp_routes] = mock_object + + request = {} + await client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_tcp_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_tcp_routes_async(transport: str = 'grpc_asyncio', request_type=tcp_route.ListTcpRoutesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tcp_route.ListTcpRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTcpRoutesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tcp_routes_async_from_dict(): + await test_list_tcp_routes_async(request_type=dict) + + +def test_list_tcp_routes_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.ListTcpRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + call.return_value = tcp_route.ListTcpRoutesResponse() + client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tcp_routes_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.ListTcpRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse()) + await client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_tcp_routes_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.ListTcpRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tcp_routes( + 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_tcp_routes_flattened_error(): + client = NetworkServicesClient( + 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_tcp_routes( + tcp_route.ListTcpRoutesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tcp_routes_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.ListTcpRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tcp_routes( + 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_tcp_routes_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tcp_routes( + tcp_route.ListTcpRoutesRequest(), + parent='parent_value', + ) + + +def test_list_tcp_routes_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_tcp_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token='abc', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token='def', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token='ghi', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_tcp_routes(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tcp_route.TcpRoute) + for i in results) +def test_list_tcp_routes_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_tcp_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token='abc', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token='def', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token='ghi', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tcp_routes(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_tcp_routes_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token='abc', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token='def', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token='ghi', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tcp_routes(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, tcp_route.TcpRoute) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tcp_routes_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tcp_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token='abc', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token='def', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token='ghi', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + 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_tcp_routes(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", [ + tcp_route.GetTcpRouteRequest, + dict, +]) +def test_get_tcp_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.TcpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + response = client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tcp_route.GetTcpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tcp_route.TcpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +def test_get_tcp_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.GetTcpRouteRequest() + + +def test_get_tcp_route_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 = NetworkServicesClient( + 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 = tcp_route.GetTcpRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_tcp_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.GetTcpRouteRequest( + name='name_value', + ) + +def test_get_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + request = {} + client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tcp_route(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_tcp_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.GetTcpRouteRequest() + +@pytest.mark.asyncio +async def test_get_tcp_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tcp_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_tcp_route] = mock_object + + request = {} + await client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_tcp_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_tcp_route_async(transport: str = 'grpc_asyncio', request_type=tcp_route.GetTcpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tcp_route.GetTcpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tcp_route.TcpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +@pytest.mark.asyncio +async def test_get_tcp_route_async_from_dict(): + await test_get_tcp_route_async(request_type=dict) + + +def test_get_tcp_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.GetTcpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + call.return_value = tcp_route.TcpRoute() + client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tcp_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.GetTcpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute()) + await client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_tcp_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.TcpRoute() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tcp_route( + 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_tcp_route_flattened_error(): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.GetTcpRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_tcp_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tcp_route.TcpRoute() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tcp_route( + 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_tcp_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tcp_route( + tcp_route.GetTcpRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tcp_route.CreateTcpRouteRequest, + dict, +]) +def test_create_tcp_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_tcp_route.CreateTcpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_tcp_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.CreateTcpRouteRequest() + + +def test_create_tcp_route_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 = NetworkServicesClient( + 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_tcp_route.CreateTcpRouteRequest( + parent='parent_value', + tcp_route_id='tcp_route_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_tcp_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.CreateTcpRouteRequest( + parent='parent_value', + tcp_route_id='tcp_route_id_value', + ) + +def test_create_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + request = {} + client.create_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__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_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.CreateTcpRouteRequest() + +@pytest.mark.asyncio +async def test_create_tcp_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tcp_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_tcp_route] = mock_object + + request = {} + await client.create_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_tcp_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_tcp_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tcp_route.CreateTcpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__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_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_tcp_route.CreateTcpRouteRequest() + 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_tcp_route_async_from_dict(): + await test_create_tcp_route_async(request_type=dict) + + +def test_create_tcp_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tcp_route.CreateTcpRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tcp_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tcp_route.CreateTcpRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_tcp_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__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_tcp_route( + parent='parent_value', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_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].tcp_route + mock_val = gcn_tcp_route.TcpRoute(name='name_value') + assert arg == mock_val + arg = args[0].tcp_route_id + mock_val = 'tcp_route_id_value' + assert arg == mock_val + + +def test_create_tcp_route_flattened_error(): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.CreateTcpRouteRequest(), + parent='parent_value', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_id_value', + ) + +@pytest.mark.asyncio +async def test_create_tcp_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tcp_route), + '__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_tcp_route( + parent='parent_value', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_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].tcp_route + mock_val = gcn_tcp_route.TcpRoute(name='name_value') + assert arg == mock_val + arg = args[0].tcp_route_id + mock_val = 'tcp_route_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_tcp_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tcp_route( + gcn_tcp_route.CreateTcpRouteRequest(), + parent='parent_value', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tcp_route.UpdateTcpRouteRequest, + dict, +]) +def test_update_tcp_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_tcp_route.UpdateTcpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_tcp_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest() + + +def test_update_tcp_route_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 = NetworkServicesClient( + 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_tcp_route.UpdateTcpRouteRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_tcp_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest( + ) + +def test_update_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + request = {} + client.update_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__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_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest() + +@pytest.mark.asyncio +async def test_update_tcp_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tcp_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_tcp_route] = mock_object + + request = {} + await client.update_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_tcp_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_tcp_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tcp_route.UpdateTcpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__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_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_tcp_route.UpdateTcpRouteRequest() + 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_tcp_route_async_from_dict(): + await test_update_tcp_route_async(request_type=dict) + + +def test_update_tcp_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tcp_route.UpdateTcpRouteRequest() + + request.tcp_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tcp_route.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tcp_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tcp_route.UpdateTcpRouteRequest() + + request.tcp_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tcp_route.name=name_value', + ) in kw['metadata'] + + +def test_update_tcp_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__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_tcp_route( + tcp_route=gcn_tcp_route.TcpRoute(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].tcp_route + mock_val = gcn_tcp_route.TcpRoute(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_tcp_route_flattened_error(): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.UpdateTcpRouteRequest(), + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_tcp_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tcp_route), + '__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_tcp_route( + tcp_route=gcn_tcp_route.TcpRoute(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].tcp_route + mock_val = gcn_tcp_route.TcpRoute(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_tcp_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tcp_route( + gcn_tcp_route.UpdateTcpRouteRequest(), + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + tcp_route.DeleteTcpRouteRequest, + dict, +]) +def test_delete_tcp_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tcp_route.DeleteTcpRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_tcp_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.DeleteTcpRouteRequest() + + +def test_delete_tcp_route_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 = NetworkServicesClient( + 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 = tcp_route.DeleteTcpRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_tcp_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.DeleteTcpRouteRequest( + name='name_value', + ) + +def test_delete_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + request = {} + client.delete_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__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_tcp_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tcp_route.DeleteTcpRouteRequest() + +@pytest.mark.asyncio +async def test_delete_tcp_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tcp_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_tcp_route] = mock_object + + request = {} + await client.delete_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_tcp_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_tcp_route_async(transport: str = 'grpc_asyncio', request_type=tcp_route.DeleteTcpRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tcp_route), + '__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_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tcp_route.DeleteTcpRouteRequest() + 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_tcp_route_async_from_dict(): + await test_delete_tcp_route_async(request_type=dict) + + +def test_delete_tcp_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.DeleteTcpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tcp_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tcp_route.DeleteTcpRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_tcp_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__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_tcp_route( + 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_tcp_route_flattened_error(): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.DeleteTcpRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_tcp_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tcp_route), + '__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_tcp_route( + 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_tcp_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tcp_route( + tcp_route.DeleteTcpRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + tls_route.ListTlsRoutesRequest, + dict, +]) +def test_list_tls_routes(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.ListTlsRoutesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tls_route.ListTlsRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTlsRoutesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tls_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_tls_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.ListTlsRoutesRequest() + + +def test_list_tls_routes_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 = NetworkServicesClient( + 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 = tls_route.ListTlsRoutesRequest( + 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_tls_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_tls_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.ListTlsRoutesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_tls_routes_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 = NetworkServicesClient( + 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_tls_routes 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_tls_routes] = mock_rpc + request = {} + client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tls_routes(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_tls_routes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tls_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.ListTlsRoutesRequest() + +@pytest.mark.asyncio +async def test_list_tls_routes_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tls_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_tls_routes] = mock_object + + request = {} + await client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_tls_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_tls_routes_async(transport: str = 'grpc_asyncio', request_type=tls_route.ListTlsRoutesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tls_route.ListTlsRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTlsRoutesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tls_routes_async_from_dict(): + await test_list_tls_routes_async(request_type=dict) + + +def test_list_tls_routes_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.ListTlsRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + call.return_value = tls_route.ListTlsRoutesResponse() + client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tls_routes_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.ListTlsRoutesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse()) + await client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_tls_routes_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.ListTlsRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tls_routes( + 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_tls_routes_flattened_error(): + client = NetworkServicesClient( + 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_tls_routes( + tls_route.ListTlsRoutesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tls_routes_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.ListTlsRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tls_routes( + 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_tls_routes_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tls_routes( + tls_route.ListTlsRoutesRequest(), + parent='parent_value', + ) + + +def test_list_tls_routes_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_tls_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token='abc', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token='def', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token='ghi', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_tls_routes(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tls_route.TlsRoute) + for i in results) +def test_list_tls_routes_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_tls_routes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token='abc', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token='def', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token='ghi', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tls_routes(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_tls_routes_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token='abc', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token='def', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token='ghi', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tls_routes(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, tls_route.TlsRoute) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tls_routes_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tls_routes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token='abc', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token='def', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token='ghi', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + 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_tls_routes(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", [ + tls_route.GetTlsRouteRequest, + dict, +]) +def test_get_tls_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.TlsRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + response = client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tls_route.GetTlsRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tls_route.TlsRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +def test_get_tls_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.GetTlsRouteRequest() + + +def test_get_tls_route_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 = NetworkServicesClient( + 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 = tls_route.GetTlsRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_tls_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.GetTlsRouteRequest( + name='name_value', + ) + +def test_get_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + request = {} + client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tls_route(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_tls_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.GetTlsRouteRequest() + +@pytest.mark.asyncio +async def test_get_tls_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tls_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_tls_route] = mock_object + + request = {} + await client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_tls_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_tls_route_async(transport: str = 'grpc_asyncio', request_type=tls_route.GetTlsRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + )) + response = await client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tls_route.GetTlsRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tls_route.TlsRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + + +@pytest.mark.asyncio +async def test_get_tls_route_async_from_dict(): + await test_get_tls_route_async(request_type=dict) + + +def test_get_tls_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.GetTlsRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + call.return_value = tls_route.TlsRoute() + client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tls_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.GetTlsRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute()) + await client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_tls_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.TlsRoute() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tls_route( + 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_tls_route_flattened_error(): + client = NetworkServicesClient( + 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_tls_route( + tls_route.GetTlsRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_tls_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tls_route.TlsRoute() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tls_route( + 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_tls_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tls_route( + tls_route.GetTlsRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tls_route.CreateTlsRouteRequest, + dict, +]) +def test_create_tls_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_tls_route.CreateTlsRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_tls_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.CreateTlsRouteRequest() + + +def test_create_tls_route_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 = NetworkServicesClient( + 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_tls_route.CreateTlsRouteRequest( + parent='parent_value', + tls_route_id='tls_route_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_tls_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.CreateTlsRouteRequest( + parent='parent_value', + tls_route_id='tls_route_id_value', + ) + +def test_create_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + request = {} + client.create_tls_route(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_tls_route(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_tls_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__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_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.CreateTlsRouteRequest() + +@pytest.mark.asyncio +async def test_create_tls_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tls_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_tls_route] = mock_object + + request = {} + await client.create_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_tls_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_tls_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tls_route.CreateTlsRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__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_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_tls_route.CreateTlsRouteRequest() + 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_tls_route_async_from_dict(): + await test_create_tls_route_async(request_type=dict) + + +def test_create_tls_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tls_route.CreateTlsRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tls_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tls_route.CreateTlsRouteRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_tls_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__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_tls_route( + parent='parent_value', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_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].tls_route + mock_val = gcn_tls_route.TlsRoute(name='name_value') + assert arg == mock_val + arg = args[0].tls_route_id + mock_val = 'tls_route_id_value' + assert arg == mock_val + + +def test_create_tls_route_flattened_error(): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.CreateTlsRouteRequest(), + parent='parent_value', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_id_value', + ) + +@pytest.mark.asyncio +async def test_create_tls_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tls_route), + '__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_tls_route( + parent='parent_value', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_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].tls_route + mock_val = gcn_tls_route.TlsRoute(name='name_value') + assert arg == mock_val + arg = args[0].tls_route_id + mock_val = 'tls_route_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_tls_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tls_route( + gcn_tls_route.CreateTlsRouteRequest(), + parent='parent_value', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tls_route.UpdateTlsRouteRequest, + dict, +]) +def test_update_tls_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_tls_route.UpdateTlsRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_tls_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.UpdateTlsRouteRequest() + + +def test_update_tls_route_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 = NetworkServicesClient( + 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_tls_route.UpdateTlsRouteRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_tls_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.UpdateTlsRouteRequest( + ) + +def test_update_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + request = {} + client.update_tls_route(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_tls_route(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_tls_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__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_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_tls_route.UpdateTlsRouteRequest() + +@pytest.mark.asyncio +async def test_update_tls_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tls_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_tls_route] = mock_object + + request = {} + await client.update_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_tls_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_tls_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tls_route.UpdateTlsRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__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_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_tls_route.UpdateTlsRouteRequest() + 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_tls_route_async_from_dict(): + await test_update_tls_route_async(request_type=dict) + + +def test_update_tls_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tls_route.UpdateTlsRouteRequest() + + request.tls_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tls_route.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tls_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_tls_route.UpdateTlsRouteRequest() + + request.tls_route.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tls_route.name=name_value', + ) in kw['metadata'] + + +def test_update_tls_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__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_tls_route( + tls_route=gcn_tls_route.TlsRoute(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].tls_route + mock_val = gcn_tls_route.TlsRoute(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_tls_route_flattened_error(): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.UpdateTlsRouteRequest(), + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_tls_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tls_route), + '__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_tls_route( + tls_route=gcn_tls_route.TlsRoute(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].tls_route + mock_val = gcn_tls_route.TlsRoute(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_tls_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tls_route( + gcn_tls_route.UpdateTlsRouteRequest(), + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + tls_route.DeleteTlsRouteRequest, + dict, +]) +def test_delete_tls_route(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tls_route.DeleteTlsRouteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_tls_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.DeleteTlsRouteRequest() + + +def test_delete_tls_route_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 = NetworkServicesClient( + 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 = tls_route.DeleteTlsRouteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_tls_route(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.DeleteTlsRouteRequest( + name='name_value', + ) + +def test_delete_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + request = {} + client.delete_tls_route(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_tls_route(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_tls_route_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__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_tls_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tls_route.DeleteTlsRouteRequest() + +@pytest.mark.asyncio +async def test_delete_tls_route_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_tls_route in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_tls_route] = mock_object + + request = {} + await client.delete_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_tls_route(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_tls_route_async(transport: str = 'grpc_asyncio', request_type=tls_route.DeleteTlsRouteRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tls_route), + '__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_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tls_route.DeleteTlsRouteRequest() + 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_tls_route_async_from_dict(): + await test_delete_tls_route_async(request_type=dict) + + +def test_delete_tls_route_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.DeleteTlsRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tls_route_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tls_route.DeleteTlsRouteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_tls_route_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__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_tls_route( + 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_tls_route_flattened_error(): + client = NetworkServicesClient( + 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_tls_route( + tls_route.DeleteTlsRouteRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_tls_route_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tls_route), + '__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_tls_route( + 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_tls_route_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tls_route( + tls_route.DeleteTlsRouteRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service_binding.ListServiceBindingsRequest, + dict, +]) +def test_list_service_bindings(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ListServiceBindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service_binding.ListServiceBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceBindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_service_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_service_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.ListServiceBindingsRequest() + + +def test_list_service_bindings_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 = NetworkServicesClient( + 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 = service_binding.ListServiceBindingsRequest( + 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_service_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_service_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.ListServiceBindingsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_service_bindings_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 = NetworkServicesClient( + 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_service_bindings 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_service_bindings] = mock_rpc + request = {} + client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_service_bindings(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_service_bindings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_service_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.ListServiceBindingsRequest() + +@pytest.mark.asyncio +async def test_list_service_bindings_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_service_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_service_bindings] = mock_object + + request = {} + await client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_service_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_service_bindings_async(transport: str = 'grpc_asyncio', request_type=service_binding.ListServiceBindingsRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service_binding.ListServiceBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceBindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_service_bindings_async_from_dict(): + await test_list_service_bindings_async(request_type=dict) + + +def test_list_service_bindings_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.ListServiceBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + call.return_value = service_binding.ListServiceBindingsResponse() + client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_service_bindings_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.ListServiceBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse()) + await client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_service_bindings_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ListServiceBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_service_bindings( + 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_service_bindings_flattened_error(): + client = NetworkServicesClient( + 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_service_bindings( + service_binding.ListServiceBindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_service_bindings_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ListServiceBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_service_bindings( + 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_service_bindings_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_service_bindings( + service_binding.ListServiceBindingsRequest(), + parent='parent_value', + ) + + +def test_list_service_bindings_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_service_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token='abc', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token='def', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token='ghi', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_service_bindings(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service_binding.ServiceBinding) + for i in results) +def test_list_service_bindings_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_service_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token='abc', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token='def', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token='ghi', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_service_bindings(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_service_bindings_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token='abc', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token='def', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token='ghi', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_service_bindings(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, service_binding.ServiceBinding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_service_bindings_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token='abc', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token='def', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token='ghi', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + 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_service_bindings(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", [ + service_binding.GetServiceBindingRequest, + dict, +]) +def test_get_service_binding(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ServiceBinding( + name='name_value', + description='description_value', + service='service_value', + ) + response = client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service_binding.GetServiceBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service_binding.ServiceBinding) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.service == 'service_value' + + +def test_get_service_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.GetServiceBindingRequest() + + +def test_get_service_binding_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 = NetworkServicesClient( + 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 = service_binding.GetServiceBindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_service_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.GetServiceBindingRequest( + name='name_value', + ) + +def test_get_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + request = {} + client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_service_binding(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_service_binding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding( + name='name_value', + description='description_value', + service='service_value', + )) + response = await client.get_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.GetServiceBindingRequest() + +@pytest.mark.asyncio +async def test_get_service_binding_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_service_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_service_binding] = mock_object + + request = {} + await client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_service_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_service_binding_async(transport: str = 'grpc_asyncio', request_type=service_binding.GetServiceBindingRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding( + name='name_value', + description='description_value', + service='service_value', + )) + response = await client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service_binding.GetServiceBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service_binding.ServiceBinding) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.service == 'service_value' + + +@pytest.mark.asyncio +async def test_get_service_binding_async_from_dict(): + await test_get_service_binding_async(request_type=dict) + + +def test_get_service_binding_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.GetServiceBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + call.return_value = service_binding.ServiceBinding() + client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_service_binding_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.GetServiceBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding()) + await client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_service_binding_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ServiceBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service_binding( + 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_service_binding_flattened_error(): + client = NetworkServicesClient( + 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_service_binding( + service_binding.GetServiceBindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_service_binding_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_binding.ServiceBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service_binding( + 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_service_binding_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service_binding( + service_binding.GetServiceBindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_service_binding.CreateServiceBindingRequest, + dict, +]) +def test_create_service_binding(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_service_binding.CreateServiceBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_service_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_service_binding.CreateServiceBindingRequest() + + +def test_create_service_binding_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 = NetworkServicesClient( + 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_service_binding.CreateServiceBindingRequest( + parent='parent_value', + service_binding_id='service_binding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_service_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_service_binding.CreateServiceBindingRequest( + parent='parent_value', + service_binding_id='service_binding_id_value', + ) + +def test_create_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + request = {} + client.create_service_binding(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_service_binding(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_service_binding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__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_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_service_binding.CreateServiceBindingRequest() + +@pytest.mark.asyncio +async def test_create_service_binding_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_service_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_service_binding] = mock_object + + request = {} + await client.create_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_service_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_service_binding_async(transport: str = 'grpc_asyncio', request_type=gcn_service_binding.CreateServiceBindingRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__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_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_service_binding.CreateServiceBindingRequest() + 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_service_binding_async_from_dict(): + await test_create_service_binding_async(request_type=dict) + + +def test_create_service_binding_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_service_binding.CreateServiceBindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_service_binding_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_service_binding.CreateServiceBindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_service_binding_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__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_service_binding( + parent='parent_value', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_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].service_binding + mock_val = gcn_service_binding.ServiceBinding(name='name_value') + assert arg == mock_val + arg = args[0].service_binding_id + mock_val = 'service_binding_id_value' + assert arg == mock_val + + +def test_create_service_binding_flattened_error(): + client = NetworkServicesClient( + 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_service_binding( + gcn_service_binding.CreateServiceBindingRequest(), + parent='parent_value', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_id_value', + ) + +@pytest.mark.asyncio +async def test_create_service_binding_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_binding), + '__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_service_binding( + parent='parent_value', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_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].service_binding + mock_val = gcn_service_binding.ServiceBinding(name='name_value') + assert arg == mock_val + arg = args[0].service_binding_id + mock_val = 'service_binding_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_service_binding_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service_binding( + gcn_service_binding.CreateServiceBindingRequest(), + parent='parent_value', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service_binding.DeleteServiceBindingRequest, + dict, +]) +def test_delete_service_binding(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service_binding.DeleteServiceBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_service_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.DeleteServiceBindingRequest() + + +def test_delete_service_binding_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 = NetworkServicesClient( + 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 = service_binding.DeleteServiceBindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_service_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.DeleteServiceBindingRequest( + name='name_value', + ) + +def test_delete_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + request = {} + client.delete_service_binding(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_service_binding(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_service_binding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__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_service_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_binding.DeleteServiceBindingRequest() + +@pytest.mark.asyncio +async def test_delete_service_binding_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_service_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_service_binding] = mock_object + + request = {} + await client.delete_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_service_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_service_binding_async(transport: str = 'grpc_asyncio', request_type=service_binding.DeleteServiceBindingRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_binding), + '__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_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service_binding.DeleteServiceBindingRequest() + 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_service_binding_async_from_dict(): + await test_delete_service_binding_async(request_type=dict) + + +def test_delete_service_binding_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.DeleteServiceBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_service_binding_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service_binding.DeleteServiceBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_service_binding_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__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_service_binding( + 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_service_binding_flattened_error(): + client = NetworkServicesClient( + 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_service_binding( + service_binding.DeleteServiceBindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_service_binding_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_binding), + '__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_service_binding( + 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_service_binding_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service_binding( + service_binding.DeleteServiceBindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + mesh.ListMeshesRequest, + dict, +]) +def test_list_meshes(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_meshes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.ListMeshesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = mesh.ListMeshesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeshesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_meshes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_meshes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.ListMeshesRequest() + + +def test_list_meshes_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 = NetworkServicesClient( + 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 = mesh.ListMeshesRequest( + 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_meshes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_meshes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.ListMeshesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_meshes_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 = NetworkServicesClient( + 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_meshes 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_meshes] = mock_rpc + request = {} + client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_meshes(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_meshes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_meshes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.ListMeshesRequest() + +@pytest.mark.asyncio +async def test_list_meshes_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_meshes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_meshes] = mock_object + + request = {} + await client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_meshes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_meshes_async(transport: str = 'grpc_asyncio', request_type=mesh.ListMeshesRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_meshes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = mesh.ListMeshesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeshesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_meshes_async_from_dict(): + await test_list_meshes_async(request_type=dict) + + +def test_list_meshes_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.ListMeshesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + call.return_value = mesh.ListMeshesResponse() + client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_meshes_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.ListMeshesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse()) + await client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_meshes_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.ListMeshesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_meshes( + 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_meshes_flattened_error(): + client = NetworkServicesClient( + 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_meshes( + mesh.ListMeshesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_meshes_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.ListMeshesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_meshes( + 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_meshes_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_meshes( + mesh.ListMeshesRequest(), + parent='parent_value', + ) + + +def test_list_meshes_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_meshes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token='abc', + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token='def', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token='ghi', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_meshes(request={}) + + assert pager._metadata == expected_metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mesh.Mesh) + for i in results) +def test_list_meshes_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + 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_meshes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token='abc', + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token='def', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token='ghi', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + RuntimeError, + ) + pages = list(client.list_meshes(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_meshes_async_pager(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token='abc', + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token='def', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token='ghi', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_meshes(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, mesh.Mesh) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_meshes_async_pages(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_meshes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token='abc', + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token='def', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token='ghi', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + 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_meshes(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", [ + mesh.GetMeshRequest, + dict, +]) +def test_get_mesh(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.Mesh( + name='name_value', + self_link='self_link_value', + description='description_value', + interception_port=1848, + ) + response = client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = mesh.GetMeshRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mesh.Mesh) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.interception_port == 1848 + + +def test_get_mesh_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.GetMeshRequest() + + +def test_get_mesh_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 = NetworkServicesClient( + 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 = mesh.GetMeshRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mesh(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.GetMeshRequest( + name='name_value', + ) + +def test_get_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + request = {} + client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mesh(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_mesh_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh( + name='name_value', + self_link='self_link_value', + description='description_value', + interception_port=1848, + )) + response = await client.get_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.GetMeshRequest() + +@pytest.mark.asyncio +async def test_get_mesh_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_mesh in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_mesh] = mock_object + + request = {} + await client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_mesh(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_mesh_async(transport: str = 'grpc_asyncio', request_type=mesh.GetMeshRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh( + name='name_value', + self_link='self_link_value', + description='description_value', + interception_port=1848, + )) + response = await client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = mesh.GetMeshRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mesh.Mesh) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.interception_port == 1848 + + +@pytest.mark.asyncio +async def test_get_mesh_async_from_dict(): + await test_get_mesh_async(request_type=dict) + + +def test_get_mesh_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.GetMeshRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + call.return_value = mesh.Mesh() + client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_mesh_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.GetMeshRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh()) + await client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_mesh_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.Mesh() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mesh( + 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_mesh_flattened_error(): + client = NetworkServicesClient( + 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_mesh( + mesh.GetMeshRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_mesh_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mesh.Mesh() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mesh( + 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_mesh_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mesh( + mesh.GetMeshRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_mesh.CreateMeshRequest, + dict, +]) +def test_create_mesh(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_mesh.CreateMeshRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_mesh_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.CreateMeshRequest() + + +def test_create_mesh_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 = NetworkServicesClient( + 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_mesh.CreateMeshRequest( + parent='parent_value', + mesh_id='mesh_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mesh(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.CreateMeshRequest( + parent='parent_value', + mesh_id='mesh_id_value', + ) + +def test_create_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + request = {} + client.create_mesh(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_mesh(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_mesh_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__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_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.CreateMeshRequest() + +@pytest.mark.asyncio +async def test_create_mesh_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_mesh in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_mesh] = mock_object + + request = {} + await client.create_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_mesh(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_mesh_async(transport: str = 'grpc_asyncio', request_type=gcn_mesh.CreateMeshRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__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_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_mesh.CreateMeshRequest() + 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_mesh_async_from_dict(): + await test_create_mesh_async(request_type=dict) + + +def test_create_mesh_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_mesh.CreateMeshRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_mesh_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_mesh.CreateMeshRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_mesh_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__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_mesh( + parent='parent_value', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_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].mesh + mock_val = gcn_mesh.Mesh(name='name_value') + assert arg == mock_val + arg = args[0].mesh_id + mock_val = 'mesh_id_value' + assert arg == mock_val + + +def test_create_mesh_flattened_error(): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.CreateMeshRequest(), + parent='parent_value', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_id_value', + ) + +@pytest.mark.asyncio +async def test_create_mesh_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mesh), + '__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_mesh( + parent='parent_value', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_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].mesh + mock_val = gcn_mesh.Mesh(name='name_value') + assert arg == mock_val + arg = args[0].mesh_id + mock_val = 'mesh_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_mesh_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mesh( + gcn_mesh.CreateMeshRequest(), + parent='parent_value', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_mesh.UpdateMeshRequest, + dict, +]) +def test_update_mesh(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_mesh.UpdateMeshRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_mesh_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.UpdateMeshRequest() + + +def test_update_mesh_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 = NetworkServicesClient( + 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_mesh.UpdateMeshRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mesh(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.UpdateMeshRequest( + ) + +def test_update_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + request = {} + client.update_mesh(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_mesh(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_mesh_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__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_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_mesh.UpdateMeshRequest() + +@pytest.mark.asyncio +async def test_update_mesh_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_mesh in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_mesh] = mock_object + + request = {} + await client.update_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_mesh(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_mesh_async(transport: str = 'grpc_asyncio', request_type=gcn_mesh.UpdateMeshRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__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_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_mesh.UpdateMeshRequest() + 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_mesh_async_from_dict(): + await test_update_mesh_async(request_type=dict) + + +def test_update_mesh_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_mesh.UpdateMeshRequest() + + request.mesh.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'mesh.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_mesh_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_mesh.UpdateMeshRequest() + + request.mesh.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'mesh.name=name_value', + ) in kw['metadata'] + + +def test_update_mesh_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__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_mesh( + mesh=gcn_mesh.Mesh(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].mesh + mock_val = gcn_mesh.Mesh(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_mesh_flattened_error(): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.UpdateMeshRequest(), + mesh=gcn_mesh.Mesh(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_mesh_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mesh), + '__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_mesh( + mesh=gcn_mesh.Mesh(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].mesh + mock_val = gcn_mesh.Mesh(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_mesh_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mesh( + gcn_mesh.UpdateMeshRequest(), + mesh=gcn_mesh.Mesh(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + mesh.DeleteMeshRequest, + dict, +]) +def test_delete_mesh(request_type, transport: str = 'grpc'): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = mesh.DeleteMeshRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_mesh_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.DeleteMeshRequest() + + +def test_delete_mesh_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 = NetworkServicesClient( + 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 = mesh.DeleteMeshRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mesh(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.DeleteMeshRequest( + name='name_value', + ) + +def test_delete_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + request = {} + client.delete_mesh(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_mesh(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_mesh_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__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_mesh() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == mesh.DeleteMeshRequest() + +@pytest.mark.asyncio +async def test_delete_mesh_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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_mesh in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_mesh] = mock_object + + request = {} + await client.delete_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_mesh(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_mesh_async(transport: str = 'grpc_asyncio', request_type=mesh.DeleteMeshRequest): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mesh), + '__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_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = mesh.DeleteMeshRequest() + 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_mesh_async_from_dict(): + await test_delete_mesh_async(request_type=dict) + + +def test_delete_mesh_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.DeleteMeshRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_mesh_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mesh.DeleteMeshRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_mesh_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__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_mesh( + 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_mesh_flattened_error(): + client = NetworkServicesClient( + 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_mesh( + mesh.DeleteMeshRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_mesh_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mesh), + '__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_mesh( + 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_mesh_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mesh( + mesh.DeleteMeshRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + endpoint_policy.ListEndpointPoliciesRequest, + dict, +]) +def test_list_endpoint_policies_rest(request_type): + client = NetworkServicesClient( + 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 = endpoint_policy.ListEndpointPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_endpoint_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policies] = mock_rpc + + request = {} + client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_endpoint_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_endpoint_policies_rest_required_fields(request_type=endpoint_policy.ListEndpointPoliciesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_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_endpoint_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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.ListEndpointPoliciesResponse() + # 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 = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_endpoint_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_endpoint_policies_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_endpoint_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_endpoint_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_endpoint_policies") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_endpoint_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.ListEndpointPoliciesRequest.pb(endpoint_policy.ListEndpointPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = endpoint_policy.ListEndpointPoliciesResponse.to_json(endpoint_policy.ListEndpointPoliciesResponse()) + + request = endpoint_policy.ListEndpointPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.ListEndpointPoliciesResponse() + + client.list_endpoint_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_endpoint_policies_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.ListEndpointPoliciesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_endpoint_policies(request) + + +def test_list_endpoint_policies_rest_flattened(): + client = NetworkServicesClient( + 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 = endpoint_policy.ListEndpointPoliciesResponse() + + # 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 = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_endpoint_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/*}/endpointPolicies" % client.transport._host, args[1]) + + +def test_list_endpoint_policies_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_endpoint_policies_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token='abc', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token='def', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token='ghi', + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(endpoint_policy.ListEndpointPoliciesResponse.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_endpoint_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) + for i in results) + + pages = list(client.list_endpoint_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + endpoint_policy.GetEndpointPolicyRequest, + dict, +]) +def test_get_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/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 = endpoint_policy.EndpointPolicy( + name='name_value', + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy='authorization_policy_value', + description='description_value', + server_tls_policy='server_tls_policy_value', + client_tls_policy='client_tls_policy_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == 'name_value' + assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + assert response.authorization_policy == 'authorization_policy_value' + assert response.description == 'description_value' + assert response.server_tls_policy == 'server_tls_policy_value' + assert response.client_tls_policy == 'client_tls_policy_value' + +def test_get_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + + request = {} + client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_endpoint_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_endpoint_policy_rest_required_fields(request_type=endpoint_policy.GetEndpointPolicyRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_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_endpoint_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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.EndpointPolicy() + # 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 = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_endpoint_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_endpoint_policy") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_endpoint_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.GetEndpointPolicyRequest.pb(endpoint_policy.GetEndpointPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = endpoint_policy.EndpointPolicy.to_json(endpoint_policy.EndpointPolicy()) + + request = endpoint_policy.GetEndpointPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.EndpointPolicy() + + client.get_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.GetEndpointPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_endpoint_policy(request) + + +def test_get_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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 = endpoint_policy.EndpointPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/endpointPolicies/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 = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_endpoint_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/*/endpointPolicies/*}" % client.transport._host, args[1]) + + +def test_get_endpoint_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name='name_value', + ) + + +def test_get_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_endpoint_policy.CreateEndpointPolicyRequest, + dict, +]) +def test_create_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["endpoint_policy"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'authorization_policy': 'authorization_policy_value', 'endpoint_matcher': {'metadata_label_matcher': {'metadata_label_match_criteria': 1, 'metadata_labels': [{'label_name': 'label_name_value', 'label_value': 'label_value_value'}]}}, 'traffic_port_selector': {'ports': ['ports_value1', 'ports_value2']}, 'description': 'description_value', 'server_tls_policy': 'server_tls_policy_value', 'client_tls_policy': 'client_tls_policy_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_endpoint_policy.CreateEndpointPolicyRequest.meta.fields["endpoint_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["endpoint_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["endpoint_policy"][field])): + del request_init["endpoint_policy"][field][i][subfield] + else: + del request_init["endpoint_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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + + request = {} + client.create_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["endpoint_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 "endpointPolicyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == request_init["endpoint_policy_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["endpointPolicyId"] = 'endpoint_policy_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_endpoint_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("endpoint_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 "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == 'endpoint_policy_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_endpoint_policy(request) + + expected_params = [ + ( + "endpointPolicyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("endpointPolicyId", )) & set(("parent", "endpointPolicyId", "endpointPolicy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_endpoint_policy") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_endpoint_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb(gcn_endpoint_policy.CreateEndpointPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_endpoint_policy(request) + + +def test_create_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_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 + + client.create_endpoint_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/*}/endpointPolicies" % client.transport._host, args[1]) + + +def test_create_endpoint_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent='parent_value', + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + endpoint_policy_id='endpoint_policy_id_value', + ) + + +def test_create_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, + dict, +]) +def test_update_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} + request_init["endpoint_policy"] = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'authorization_policy': 'authorization_policy_value', 'endpoint_matcher': {'metadata_label_matcher': {'metadata_label_match_criteria': 1, 'metadata_labels': [{'label_name': 'label_name_value', 'label_value': 'label_value_value'}]}}, 'traffic_port_selector': {'ports': ['ports_value1', 'ports_value2']}, 'description': 'description_value', 'server_tls_policy': 'server_tls_policy_value', 'client_tls_policy': 'client_tls_policy_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_endpoint_policy.UpdateEndpointPolicyRequest.meta.fields["endpoint_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["endpoint_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["endpoint_policy"][field])): + del request_init["endpoint_policy"][field][i][subfield] + else: + del request_init["endpoint_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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + + request = {} + client.update_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_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_endpoint_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 = NetworkServicesClient( + 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 + + response = client.update_endpoint_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("endpointPolicy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_endpoint_policy") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_endpoint_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb(gcn_endpoint_policy.UpdateEndpointPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_endpoint_policy(request) + + +def test_update_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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 = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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 + + client.update_endpoint_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/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}" % client.transport._host, args[1]) + + +def test_update_endpoint_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + endpoint_policy.DeleteEndpointPolicyRequest, + dict, +]) +def test_delete_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_endpoint_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 = NetworkServicesClient( + 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_endpoint_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_endpoint_policy] = mock_rpc + + request = {} + client.delete_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=endpoint_policy.DeleteEndpointPolicyRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_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_endpoint_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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_endpoint_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_endpoint_policy") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_endpoint_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.DeleteEndpointPolicyRequest.pb(endpoint_policy.DeleteEndpointPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = endpoint_policy.DeleteEndpointPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.DeleteEndpointPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_endpoint_policy(request) + + +def test_delete_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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/endpointPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_endpoint_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/*/endpointPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_endpoint_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name='name_value', + ) + + +def test_delete_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gateway.ListGatewaysRequest, + dict, +]) +def test_list_gateways_rest(request_type): + client = NetworkServicesClient( + 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 = gateway.ListGatewaysResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gateway.ListGatewaysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_gateways(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGatewaysPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_gateways_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 = NetworkServicesClient( + 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_gateways 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_gateways] = mock_rpc + + request = {} + client.list_gateways(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gateways(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_gateways_rest_required_fields(request_type=gateway.ListGatewaysRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_gateways._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_gateways._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gateway.ListGatewaysResponse() + # 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 = gateway.ListGatewaysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_gateways(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_gateways_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_gateways._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_gateways_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_gateways") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_gateways") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.ListGatewaysRequest.pb(gateway.ListGatewaysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gateway.ListGatewaysResponse.to_json(gateway.ListGatewaysResponse()) + + request = gateway.ListGatewaysRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gateway.ListGatewaysResponse() + + client.list_gateways(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_gateways_rest_bad_request(transport: str = 'rest', request_type=gateway.ListGatewaysRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_gateways(request) + + +def test_list_gateways_rest_flattened(): + client = NetworkServicesClient( + 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 = gateway.ListGatewaysResponse() + + # 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 = gateway.ListGatewaysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_gateways(**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/*}/gateways" % client.transport._host, args[1]) + + +def test_list_gateways_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_gateways( + gateway.ListGatewaysRequest(), + parent='parent_value', + ) + + +def test_list_gateways_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token='abc', + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token='def', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token='ghi', + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gateway.ListGatewaysResponse.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_gateways(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gateway.Gateway) + for i in results) + + pages = list(client.list_gateways(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + gateway.GetGatewayRequest, + dict, +]) +def test_get_gateway_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/gateways/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 = gateway.Gateway( + name='name_value', + self_link='self_link_value', + description='description_value', + type_=gateway.Gateway.Type.OPEN_MESH, + ports=[568], + scope='scope_value', + server_tls_policy='server_tls_policy_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gateway.Gateway.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_gateway(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gateway.Gateway) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.type_ == gateway.Gateway.Type.OPEN_MESH + assert response.ports == [568] + assert response.scope == 'scope_value' + assert response.server_tls_policy == 'server_tls_policy_value' + +def test_get_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + + request = {} + client.get_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_gateway(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_gateway_rest_required_fields(request_type=gateway.GetGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_gateway._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_gateway._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gateway.Gateway() + # 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 = gateway.Gateway.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_gateway(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_gateway_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_gateway_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_gateway") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.GetGatewayRequest.pb(gateway.GetGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gateway.Gateway.to_json(gateway.Gateway()) + + request = gateway.GetGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gateway.Gateway() + + client.get_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_gateway_rest_bad_request(transport: str = 'rest', request_type=gateway.GetGatewayRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_gateway(request) + + +def test_get_gateway_rest_flattened(): + client = NetworkServicesClient( + 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 = gateway.Gateway() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/gateways/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 = gateway.Gateway.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_gateway(**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/*/gateways/*}" % client.transport._host, args[1]) + + +def test_get_gateway_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_gateway( + gateway.GetGatewayRequest(), + name='name_value', + ) + + +def test_get_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_gateway.CreateGatewayRequest, + dict, +]) +def test_create_gateway_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["gateway"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'type_': 1, 'ports': [569, 570], 'scope': 'scope_value', 'server_tls_policy': 'server_tls_policy_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_gateway.CreateGatewayRequest.meta.fields["gateway"] + + 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["gateway"].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["gateway"][field])): + del request_init["gateway"][field][i][subfield] + else: + del request_init["gateway"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + + request = {} + client.create_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gcn_gateway.CreateGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gateway_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 "gatewayId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == request_init["gateway_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["gatewayId"] = 'gateway_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_gateway._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("gateway_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 "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == 'gateway_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_gateway(request) + + expected_params = [ + ( + "gatewayId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_gateway_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(("gatewayId", )) & set(("parent", "gatewayId", "gateway", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_gateway_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_gateway") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_gateway.CreateGatewayRequest.pb(gcn_gateway.CreateGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_gateway.CreateGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_gateway_rest_bad_request(transport: str = 'rest', request_type=gcn_gateway.CreateGatewayRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_gateway(request) + + +def test_create_gateway_rest_flattened(): + client = NetworkServicesClient( + 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', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_gateway(**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/*}/gateways" % client.transport._host, args[1]) + + +def test_create_gateway_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_gateway( + gcn_gateway.CreateGatewayRequest(), + parent='parent_value', + gateway=gcn_gateway.Gateway(name='name_value'), + gateway_id='gateway_id_value', + ) + + +def test_create_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_gateway.UpdateGatewayRequest, + dict, +]) +def test_update_gateway_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} + request_init["gateway"] = {'name': 'projects/sample1/locations/sample2/gateways/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'type_': 1, 'ports': [569, 570], 'scope': 'scope_value', 'server_tls_policy': 'server_tls_policy_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_gateway.UpdateGatewayRequest.meta.fields["gateway"] + + 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["gateway"].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["gateway"][field])): + del request_init["gateway"][field][i][subfield] + else: + del request_init["gateway"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + + request = {} + client.update_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gcn_gateway.UpdateGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_gateway._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_gateway._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 = NetworkServicesClient( + 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 + + response = client.update_gateway(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_gateway_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("gateway", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_gateway_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_gateway") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_gateway.UpdateGatewayRequest.pb(gcn_gateway.UpdateGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_gateway.UpdateGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_gateway_rest_bad_request(transport: str = 'rest', request_type=gcn_gateway.UpdateGatewayRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_gateway(request) + + +def test_update_gateway_rest_flattened(): + client = NetworkServicesClient( + 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 = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + gateway=gcn_gateway.Gateway(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 + + client.update_gateway(**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/{gateway.name=projects/*/locations/*/gateways/*}" % client.transport._host, args[1]) + + +def test_update_gateway_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_gateway( + gcn_gateway.UpdateGatewayRequest(), + gateway=gcn_gateway.Gateway(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gateway.DeleteGatewayRequest, + dict, +]) +def test_delete_gateway_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_gateway_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 = NetworkServicesClient( + 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_gateway 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_gateway] = mock_rpc + + request = {} + client.delete_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gateway.DeleteGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_gateway._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_gateway._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_gateway(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_gateway_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_gateway_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_gateway") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.DeleteGatewayRequest.pb(gateway.DeleteGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gateway.DeleteGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_gateway_rest_bad_request(transport: str = 'rest', request_type=gateway.DeleteGatewayRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_gateway(request) + + +def test_delete_gateway_rest_flattened(): + client = NetworkServicesClient( + 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/gateways/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_gateway(**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/*/gateways/*}" % client.transport._host, args[1]) + + +def test_delete_gateway_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_gateway( + gateway.DeleteGatewayRequest(), + name='name_value', + ) + + +def test_delete_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + grpc_route.ListGrpcRoutesRequest, + dict, +]) +def test_list_grpc_routes_rest(request_type): + client = NetworkServicesClient( + 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 = grpc_route.ListGrpcRoutesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grpc_route.ListGrpcRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_grpc_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGrpcRoutesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_grpc_routes_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 = NetworkServicesClient( + 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_grpc_routes 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_grpc_routes] = mock_rpc + + request = {} + client.list_grpc_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_grpc_routes(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_grpc_routes_rest_required_fields(request_type=grpc_route.ListGrpcRoutesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_routes._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_grpc_routes._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grpc_route.ListGrpcRoutesResponse() + # 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 = grpc_route.ListGrpcRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_grpc_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_grpc_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_grpc_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_grpc_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_grpc_routes") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_grpc_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.ListGrpcRoutesRequest.pb(grpc_route.ListGrpcRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = grpc_route.ListGrpcRoutesResponse.to_json(grpc_route.ListGrpcRoutesResponse()) + + request = grpc_route.ListGrpcRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grpc_route.ListGrpcRoutesResponse() + + client.list_grpc_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_grpc_routes_rest_bad_request(transport: str = 'rest', request_type=grpc_route.ListGrpcRoutesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_grpc_routes(request) + + +def test_list_grpc_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = grpc_route.ListGrpcRoutesResponse() + + # 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 = grpc_route.ListGrpcRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_grpc_routes(**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/*}/grpcRoutes" % client.transport._host, args[1]) + + +def test_list_grpc_routes_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_grpc_routes( + grpc_route.ListGrpcRoutesRequest(), + parent='parent_value', + ) + + +def test_list_grpc_routes_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token='abc', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token='def', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token='ghi', + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grpc_route.ListGrpcRoutesResponse.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_grpc_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grpc_route.GrpcRoute) + for i in results) + + pages = list(client.list_grpc_routes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + grpc_route.GetGrpcRouteRequest, + dict, +]) +def test_get_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grpc_route.GrpcRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_grpc_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grpc_route.GrpcRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + +def test_get_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + + request = {} + client.get_grpc_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_grpc_route(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_grpc_route_rest_required_fields(request_type=grpc_route.GetGrpcRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grpc_route.GrpcRoute() + # 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 = grpc_route.GrpcRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_grpc_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_grpc_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_grpc_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.GetGrpcRouteRequest.pb(grpc_route.GetGrpcRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = grpc_route.GrpcRoute.to_json(grpc_route.GrpcRoute()) + + request = grpc_route.GetGrpcRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grpc_route.GrpcRoute() + + client.get_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_grpc_route_rest_bad_request(transport: str = 'rest', request_type=grpc_route.GetGrpcRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_grpc_route(request) + + +def test_get_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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 = grpc_route.GrpcRoute() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, args[1]) + + +def test_get_grpc_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.GetGrpcRouteRequest(), + name='name_value', + ) + + +def test_get_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_grpc_route.CreateGrpcRouteRequest, + dict, +]) +def test_create_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["grpc_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'rules': [{'matches': [{'method': {'type_': 1, 'grpc_service': 'grpc_service_value', 'grpc_method': 'grpc_method_value', 'case_sensitive': True}, 'headers': [{'type_': 1, 'key': 'key_value', 'value': 'value_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197}}}]} + # 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_grpc_route.CreateGrpcRouteRequest.meta.fields["grpc_route"] + + 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["grpc_route"].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["grpc_route"][field])): + del request_init["grpc_route"][field][i][subfield] + else: + del request_init["grpc_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + + request = {} + client.create_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=gcn_grpc_route.CreateGrpcRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["grpc_route_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 "grpcRouteId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_grpc_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "grpcRouteId" in jsonified_request + assert jsonified_request["grpcRouteId"] == request_init["grpc_route_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["grpcRouteId"] = 'grpc_route_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_grpc_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("grpc_route_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 "grpcRouteId" in jsonified_request + assert jsonified_request["grpcRouteId"] == 'grpc_route_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_grpc_route(request) + + expected_params = [ + ( + "grpcRouteId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("grpcRouteId", )) & set(("parent", "grpcRouteId", "grpcRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_grpc_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_grpc_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_grpc_route.CreateGrpcRouteRequest.pb(gcn_grpc_route.CreateGrpcRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_grpc_route.CreateGrpcRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_grpc_route_rest_bad_request(transport: str = 'rest', request_type=gcn_grpc_route.CreateGrpcRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_grpc_route(request) + + +def test_create_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_grpc_route(**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/*}/grpcRoutes" % client.transport._host, args[1]) + + +def test_create_grpc_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.CreateGrpcRouteRequest(), + parent='parent_value', + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + grpc_route_id='grpc_route_id_value', + ) + + +def test_create_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_grpc_route.UpdateGrpcRouteRequest, + dict, +]) +def test_update_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} + request_init["grpc_route"] = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'rules': [{'matches': [{'method': {'type_': 1, 'grpc_service': 'grpc_service_value', 'grpc_method': 'grpc_method_value', 'case_sensitive': True}, 'headers': [{'type_': 1, 'key': 'key_value', 'value': 'value_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197}}}]} + # 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_grpc_route.UpdateGrpcRouteRequest.meta.fields["grpc_route"] + + 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["grpc_route"].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["grpc_route"][field])): + del request_init["grpc_route"][field][i][subfield] + else: + del request_init["grpc_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + + request = {} + client.update_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=gcn_grpc_route.UpdateGrpcRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + 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 + + response = client.update_grpc_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("grpcRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_grpc_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_grpc_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_grpc_route.UpdateGrpcRouteRequest.pb(gcn_grpc_route.UpdateGrpcRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_grpc_route.UpdateGrpcRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_grpc_route_rest_bad_request(transport: str = 'rest', request_type=gcn_grpc_route.UpdateGrpcRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_grpc_route(request) + + +def test_update_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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 = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + grpc_route=gcn_grpc_route.GrpcRoute(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 + + client.update_grpc_route(**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/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}" % client.transport._host, args[1]) + + +def test_update_grpc_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.UpdateGrpcRouteRequest(), + grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + grpc_route.DeleteGrpcRouteRequest, + dict, +]) +def test_delete_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_grpc_route_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 = NetworkServicesClient( + 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_grpc_route 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_grpc_route] = mock_rpc + + request = {} + client.delete_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=grpc_route.DeleteGrpcRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_grpc_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_grpc_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_grpc_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.DeleteGrpcRouteRequest.pb(grpc_route.DeleteGrpcRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = grpc_route.DeleteGrpcRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_grpc_route_rest_bad_request(transport: str = 'rest', request_type=grpc_route.DeleteGrpcRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_grpc_route(request) + + +def test_delete_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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/grpcRoutes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, args[1]) + + +def test_delete_grpc_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.DeleteGrpcRouteRequest(), + name='name_value', + ) + + +def test_delete_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + http_route.ListHttpRoutesRequest, + dict, +]) +def test_list_http_routes_rest(request_type): + client = NetworkServicesClient( + 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 = http_route.ListHttpRoutesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = http_route.ListHttpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_http_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHttpRoutesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_http_routes_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 = NetworkServicesClient( + 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_http_routes 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_http_routes] = mock_rpc + + request = {} + client.list_http_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_http_routes(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_http_routes_rest_required_fields(request_type=http_route.ListHttpRoutesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_http_routes._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_http_routes._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = http_route.ListHttpRoutesResponse() + # 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 = http_route.ListHttpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_http_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_http_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_http_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_http_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_http_routes") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_http_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.ListHttpRoutesRequest.pb(http_route.ListHttpRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = http_route.ListHttpRoutesResponse.to_json(http_route.ListHttpRoutesResponse()) + + request = http_route.ListHttpRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = http_route.ListHttpRoutesResponse() + + client.list_http_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_http_routes_rest_bad_request(transport: str = 'rest', request_type=http_route.ListHttpRoutesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_http_routes(request) + + +def test_list_http_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = http_route.ListHttpRoutesResponse() + + # 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 = http_route.ListHttpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_http_routes(**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/*}/httpRoutes" % client.transport._host, args[1]) + + +def test_list_http_routes_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_http_routes( + http_route.ListHttpRoutesRequest(), + parent='parent_value', + ) + + +def test_list_http_routes_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token='abc', + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token='def', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token='ghi', + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(http_route.ListHttpRoutesResponse.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_http_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, http_route.HttpRoute) + for i in results) + + pages = list(client.list_http_routes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + http_route.GetHttpRouteRequest, + dict, +]) +def test_get_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + hostnames=['hostnames_value'], + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = http_route.HttpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_http_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, http_route.HttpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.hostnames == ['hostnames_value'] + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + +def test_get_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + + request = {} + client.get_http_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_http_route(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_http_route_rest_required_fields(request_type=http_route.GetHttpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = http_route.HttpRoute() + # 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 = http_route.HttpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_http_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_http_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_http_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.GetHttpRouteRequest.pb(http_route.GetHttpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = http_route.HttpRoute.to_json(http_route.HttpRoute()) + + request = http_route.GetHttpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = http_route.HttpRoute() + + client.get_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_http_route_rest_bad_request(transport: str = 'rest', request_type=http_route.GetHttpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_http_route(request) + + +def test_get_http_route_rest_flattened(): + client = NetworkServicesClient( + 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 = http_route.HttpRoute() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_http_route(**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/*/httpRoutes/*}" % client.transport._host, args[1]) + + +def test_get_http_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_http_route( + http_route.GetHttpRouteRequest(), + name='name_value', + ) + + +def test_get_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_http_route.CreateHttpRouteRequest, + dict, +]) +def test_create_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["http_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}, 'rules': [{'matches': [{'full_path_match': 'full_path_match_value', 'prefix_match': 'prefix_match_value', 'regex_match': 'regex_match_value', 'ignore_case': True, 'headers': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'prefix_match': 'prefix_match_value', 'present_match': True, 'suffix_match': 'suffix_match_value', 'range_match': {'start': 558, 'end': 311}, 'header': 'header_value', 'invert_match': True}], 'query_parameters': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'present_match': True, 'query_parameter': 'query_parameter_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'redirect': {'host_redirect': 'host_redirect_value', 'path_redirect': 'path_redirect_value', 'prefix_rewrite': 'prefix_rewrite_value', 'response_code': 1, 'https_redirect': True, 'strip_query': True, 'port_redirect': 1398}, 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'request_header_modifier': {'set': {}, 'add': {}, 'remove': ['remove_value1', 'remove_value2']}, 'response_header_modifier': {}, 'url_rewrite': {'path_prefix_rewrite': 'path_prefix_rewrite_value', 'host_rewrite': 'host_rewrite_value'}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197, 'per_try_timeout': {}}, 'request_mirror_policy': {'destination': {}}, 'cors_policy': {'allow_origins': ['allow_origins_value1', 'allow_origins_value2'], 'allow_origin_regexes': ['allow_origin_regexes_value1', 'allow_origin_regexes_value2'], 'allow_methods': ['allow_methods_value1', 'allow_methods_value2'], 'allow_headers': ['allow_headers_value1', 'allow_headers_value2'], 'expose_headers': ['expose_headers_value1', 'expose_headers_value2'], 'max_age': 'max_age_value', 'allow_credentials': True, 'disabled': True}}}]} + # 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_http_route.CreateHttpRouteRequest.meta.fields["http_route"] + + 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["http_route"].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["http_route"][field])): + del request_init["http_route"][field][i][subfield] + else: + del request_init["http_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + + request = {} + client.create_http_route(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_http_route(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_http_route_rest_required_fields(request_type=gcn_http_route.CreateHttpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["http_route_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 "httpRouteId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_http_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "httpRouteId" in jsonified_request + assert jsonified_request["httpRouteId"] == request_init["http_route_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["httpRouteId"] = 'http_route_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_http_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("http_route_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 "httpRouteId" in jsonified_request + assert jsonified_request["httpRouteId"] == 'http_route_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_http_route(request) + + expected_params = [ + ( + "httpRouteId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("httpRouteId", )) & set(("parent", "httpRouteId", "httpRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_http_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_http_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_http_route.CreateHttpRouteRequest.pb(gcn_http_route.CreateHttpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_http_route.CreateHttpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_http_route_rest_bad_request(transport: str = 'rest', request_type=gcn_http_route.CreateHttpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_http_route(request) + + +def test_create_http_route_rest_flattened(): + client = NetworkServicesClient( + 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', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_http_route(**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/*}/httpRoutes" % client.transport._host, args[1]) + + +def test_create_http_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.CreateHttpRouteRequest(), + parent='parent_value', + http_route=gcn_http_route.HttpRoute(name='name_value'), + http_route_id='http_route_id_value', + ) + + +def test_create_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_http_route.UpdateHttpRouteRequest, + dict, +]) +def test_update_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} + request_init["http_route"] = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3', 'self_link': 'self_link_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}, 'rules': [{'matches': [{'full_path_match': 'full_path_match_value', 'prefix_match': 'prefix_match_value', 'regex_match': 'regex_match_value', 'ignore_case': True, 'headers': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'prefix_match': 'prefix_match_value', 'present_match': True, 'suffix_match': 'suffix_match_value', 'range_match': {'start': 558, 'end': 311}, 'header': 'header_value', 'invert_match': True}], 'query_parameters': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'present_match': True, 'query_parameter': 'query_parameter_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'redirect': {'host_redirect': 'host_redirect_value', 'path_redirect': 'path_redirect_value', 'prefix_rewrite': 'prefix_rewrite_value', 'response_code': 1, 'https_redirect': True, 'strip_query': True, 'port_redirect': 1398}, 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'request_header_modifier': {'set': {}, 'add': {}, 'remove': ['remove_value1', 'remove_value2']}, 'response_header_modifier': {}, 'url_rewrite': {'path_prefix_rewrite': 'path_prefix_rewrite_value', 'host_rewrite': 'host_rewrite_value'}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197, 'per_try_timeout': {}}, 'request_mirror_policy': {'destination': {}}, 'cors_policy': {'allow_origins': ['allow_origins_value1', 'allow_origins_value2'], 'allow_origin_regexes': ['allow_origin_regexes_value1', 'allow_origin_regexes_value2'], 'allow_methods': ['allow_methods_value1', 'allow_methods_value2'], 'allow_headers': ['allow_headers_value1', 'allow_headers_value2'], 'expose_headers': ['expose_headers_value1', 'expose_headers_value2'], 'max_age': 'max_age_value', 'allow_credentials': True, 'disabled': True}}}]} + # 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_http_route.UpdateHttpRouteRequest.meta.fields["http_route"] + + 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["http_route"].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["http_route"][field])): + del request_init["http_route"][field][i][subfield] + else: + del request_init["http_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + + request = {} + client.update_http_route(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_http_route(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_http_route_rest_required_fields(request_type=gcn_http_route.UpdateHttpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + 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 + + response = client.update_http_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("httpRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_http_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_http_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_http_route.UpdateHttpRouteRequest.pb(gcn_http_route.UpdateHttpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_http_route.UpdateHttpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_http_route_rest_bad_request(transport: str = 'rest', request_type=gcn_http_route.UpdateHttpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_http_route(request) + + +def test_update_http_route_rest_flattened(): + client = NetworkServicesClient( + 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 = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + http_route=gcn_http_route.HttpRoute(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 + + client.update_http_route(**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/{http_route.name=projects/*/locations/*/httpRoutes/*}" % client.transport._host, args[1]) + + +def test_update_http_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.UpdateHttpRouteRequest(), + http_route=gcn_http_route.HttpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + http_route.DeleteHttpRouteRequest, + dict, +]) +def test_delete_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_http_route_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 = NetworkServicesClient( + 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_http_route 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_http_route] = mock_rpc + + request = {} + client.delete_http_route(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_http_route(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_http_route_rest_required_fields(request_type=http_route.DeleteHttpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_http_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_http_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_http_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.DeleteHttpRouteRequest.pb(http_route.DeleteHttpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = http_route.DeleteHttpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_http_route_rest_bad_request(transport: str = 'rest', request_type=http_route.DeleteHttpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_http_route(request) + + +def test_delete_http_route_rest_flattened(): + client = NetworkServicesClient( + 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/httpRoutes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_http_route(**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/*/httpRoutes/*}" % client.transport._host, args[1]) + + +def test_delete_http_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_http_route( + http_route.DeleteHttpRouteRequest(), + name='name_value', + ) + + +def test_delete_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tcp_route.ListTcpRoutesRequest, + dict, +]) +def test_list_tcp_routes_rest(request_type): + client = NetworkServicesClient( + 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 = tcp_route.ListTcpRoutesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tcp_route.ListTcpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tcp_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTcpRoutesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_tcp_routes_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 = NetworkServicesClient( + 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_tcp_routes 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_tcp_routes] = mock_rpc + + request = {} + client.list_tcp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tcp_routes(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_tcp_routes_rest_required_fields(request_type=tcp_route.ListTcpRoutesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_routes._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_tcp_routes._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tcp_route.ListTcpRoutesResponse() + # 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 = tcp_route.ListTcpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tcp_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tcp_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tcp_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tcp_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tcp_routes") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_tcp_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.ListTcpRoutesRequest.pb(tcp_route.ListTcpRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tcp_route.ListTcpRoutesResponse.to_json(tcp_route.ListTcpRoutesResponse()) + + request = tcp_route.ListTcpRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tcp_route.ListTcpRoutesResponse() + + client.list_tcp_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tcp_routes_rest_bad_request(transport: str = 'rest', request_type=tcp_route.ListTcpRoutesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tcp_routes(request) + + +def test_list_tcp_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = tcp_route.ListTcpRoutesResponse() + + # 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 = tcp_route.ListTcpRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tcp_routes(**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/*}/tcpRoutes" % client.transport._host, args[1]) + + +def test_list_tcp_routes_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tcp_routes( + tcp_route.ListTcpRoutesRequest(), + parent='parent_value', + ) + + +def test_list_tcp_routes_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token='abc', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token='def', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token='ghi', + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tcp_route.ListTcpRoutesResponse.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_tcp_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tcp_route.TcpRoute) + for i in results) + + pages = list(client.list_tcp_routes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + tcp_route.GetTcpRouteRequest, + dict, +]) +def test_get_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tcp_route.TcpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_tcp_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tcp_route.TcpRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + +def test_get_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + + request = {} + client.get_tcp_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tcp_route(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_tcp_route_rest_required_fields(request_type=tcp_route.GetTcpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tcp_route.TcpRoute() + # 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 = tcp_route.TcpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_tcp_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tcp_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_tcp_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.GetTcpRouteRequest.pb(tcp_route.GetTcpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tcp_route.TcpRoute.to_json(tcp_route.TcpRoute()) + + request = tcp_route.GetTcpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tcp_route.TcpRoute() + + client.get_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tcp_route_rest_bad_request(transport: str = 'rest', request_type=tcp_route.GetTcpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_tcp_route(request) + + +def test_get_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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 = tcp_route.TcpRoute() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, args[1]) + + +def test_get_tcp_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.GetTcpRouteRequest(), + name='name_value', + ) + + +def test_get_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tcp_route.CreateTcpRouteRequest, + dict, +]) +def test_create_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["tcp_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'address': 'address_value', 'port': 'port_value'}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'original_destination': True}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}} + # 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_tcp_route.CreateTcpRouteRequest.meta.fields["tcp_route"] + + 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["tcp_route"].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["tcp_route"][field])): + del request_init["tcp_route"][field][i][subfield] + else: + del request_init["tcp_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + + request = {} + client.create_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=gcn_tcp_route.CreateTcpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["tcp_route_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 "tcpRouteId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tcp_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "tcpRouteId" in jsonified_request + assert jsonified_request["tcpRouteId"] == request_init["tcp_route_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["tcpRouteId"] = 'tcp_route_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tcp_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("tcp_route_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 "tcpRouteId" in jsonified_request + assert jsonified_request["tcpRouteId"] == 'tcp_route_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_tcp_route(request) + + expected_params = [ + ( + "tcpRouteId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("tcpRouteId", )) & set(("parent", "tcpRouteId", "tcpRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tcp_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_tcp_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tcp_route.CreateTcpRouteRequest.pb(gcn_tcp_route.CreateTcpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_tcp_route.CreateTcpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tcp_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tcp_route.CreateTcpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_tcp_route(request) + + +def test_create_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_tcp_route(**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/*}/tcpRoutes" % client.transport._host, args[1]) + + +def test_create_tcp_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.CreateTcpRouteRequest(), + parent='parent_value', + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + tcp_route_id='tcp_route_id_value', + ) + + +def test_create_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tcp_route.UpdateTcpRouteRequest, + dict, +]) +def test_update_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} + request_init["tcp_route"] = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'address': 'address_value', 'port': 'port_value'}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'original_destination': True}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}} + # 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_tcp_route.UpdateTcpRouteRequest.meta.fields["tcp_route"] + + 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["tcp_route"].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["tcp_route"][field])): + del request_init["tcp_route"][field][i][subfield] + else: + del request_init["tcp_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + + request = {} + client.update_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=gcn_tcp_route.UpdateTcpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + 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 + + response = client.update_tcp_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("tcpRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tcp_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_tcp_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tcp_route.UpdateTcpRouteRequest.pb(gcn_tcp_route.UpdateTcpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_tcp_route.UpdateTcpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tcp_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tcp_route.UpdateTcpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_tcp_route(request) + + +def test_update_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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 = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + tcp_route=gcn_tcp_route.TcpRoute(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 + + client.update_tcp_route(**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/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}" % client.transport._host, args[1]) + + +def test_update_tcp_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.UpdateTcpRouteRequest(), + tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tcp_route.DeleteTcpRouteRequest, + dict, +]) +def test_delete_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_tcp_route_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 = NetworkServicesClient( + 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_tcp_route 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_tcp_route] = mock_rpc + + request = {} + client.delete_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=tcp_route.DeleteTcpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_tcp_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tcp_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_tcp_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.DeleteTcpRouteRequest.pb(tcp_route.DeleteTcpRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tcp_route.DeleteTcpRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tcp_route_rest_bad_request(transport: str = 'rest', request_type=tcp_route.DeleteTcpRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_tcp_route(request) + + +def test_delete_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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/tcpRoutes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, args[1]) + + +def test_delete_tcp_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.DeleteTcpRouteRequest(), + name='name_value', + ) + + +def test_delete_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tls_route.ListTlsRoutesRequest, + dict, +]) +def test_list_tls_routes_rest(request_type): + client = NetworkServicesClient( + 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 = tls_route.ListTlsRoutesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tls_route.ListTlsRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tls_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTlsRoutesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_tls_routes_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 = NetworkServicesClient( + 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_tls_routes 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_tls_routes] = mock_rpc + + request = {} + client.list_tls_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tls_routes(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_tls_routes_rest_required_fields(request_type=tls_route.ListTlsRoutesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_routes._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_tls_routes._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tls_route.ListTlsRoutesResponse() + # 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 = tls_route.ListTlsRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tls_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tls_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tls_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tls_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tls_routes") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_tls_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.ListTlsRoutesRequest.pb(tls_route.ListTlsRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tls_route.ListTlsRoutesResponse.to_json(tls_route.ListTlsRoutesResponse()) + + request = tls_route.ListTlsRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tls_route.ListTlsRoutesResponse() + + client.list_tls_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tls_routes_rest_bad_request(transport: str = 'rest', request_type=tls_route.ListTlsRoutesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tls_routes(request) + + +def test_list_tls_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = tls_route.ListTlsRoutesResponse() + + # 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 = tls_route.ListTlsRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tls_routes(**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/*}/tlsRoutes" % client.transport._host, args[1]) + + +def test_list_tls_routes_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tls_routes( + tls_route.ListTlsRoutesRequest(), + parent='parent_value', + ) + + +def test_list_tls_routes_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token='abc', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token='def', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token='ghi', + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tls_route.ListTlsRoutesResponse.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_tls_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tls_route.TlsRoute) + for i in results) + + pages = list(client.list_tls_routes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + tls_route.GetTlsRouteRequest, + dict, +]) +def test_get_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute( + name='name_value', + self_link='self_link_value', + description='description_value', + meshes=['meshes_value'], + gateways=['gateways_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tls_route.TlsRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_tls_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tls_route.TlsRoute) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.meshes == ['meshes_value'] + assert response.gateways == ['gateways_value'] + +def test_get_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + + request = {} + client.get_tls_route(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tls_route(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_tls_route_rest_required_fields(request_type=tls_route.GetTlsRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tls_route.TlsRoute() + # 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 = tls_route.TlsRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_tls_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tls_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_tls_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.GetTlsRouteRequest.pb(tls_route.GetTlsRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tls_route.TlsRoute.to_json(tls_route.TlsRoute()) + + request = tls_route.GetTlsRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tls_route.TlsRoute() + + client.get_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tls_route_rest_bad_request(transport: str = 'rest', request_type=tls_route.GetTlsRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_tls_route(request) + + +def test_get_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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 = tls_route.TlsRoute() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, args[1]) + + +def test_get_tls_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tls_route( + tls_route.GetTlsRouteRequest(), + name='name_value', + ) + + +def test_get_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tls_route.CreateTlsRouteRequest, + dict, +]) +def test_create_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["tls_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'sni_host': ['sni_host_value1', 'sni_host_value2'], 'alpn': ['alpn_value1', 'alpn_value2']}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}]}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2']} + # 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_tls_route.CreateTlsRouteRequest.meta.fields["tls_route"] + + 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["tls_route"].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["tls_route"][field])): + del request_init["tls_route"][field][i][subfield] + else: + del request_init["tls_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + + request = {} + client.create_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=gcn_tls_route.CreateTlsRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["tls_route_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 "tlsRouteId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tls_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "tlsRouteId" in jsonified_request + assert jsonified_request["tlsRouteId"] == request_init["tls_route_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["tlsRouteId"] = 'tls_route_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tls_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("tls_route_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 "tlsRouteId" in jsonified_request + assert jsonified_request["tlsRouteId"] == 'tls_route_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_tls_route(request) + + expected_params = [ + ( + "tlsRouteId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("tlsRouteId", )) & set(("parent", "tlsRouteId", "tlsRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tls_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_tls_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tls_route.CreateTlsRouteRequest.pb(gcn_tls_route.CreateTlsRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_tls_route.CreateTlsRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tls_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tls_route.CreateTlsRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_tls_route(request) + + +def test_create_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_tls_route(**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/*}/tlsRoutes" % client.transport._host, args[1]) + + +def test_create_tls_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.CreateTlsRouteRequest(), + parent='parent_value', + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + tls_route_id='tls_route_id_value', + ) + + +def test_create_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_tls_route.UpdateTlsRouteRequest, + dict, +]) +def test_update_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} + request_init["tls_route"] = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'sni_host': ['sni_host_value1', 'sni_host_value2'], 'alpn': ['alpn_value1', 'alpn_value2']}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}]}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2']} + # 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_tls_route.UpdateTlsRouteRequest.meta.fields["tls_route"] + + 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["tls_route"].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["tls_route"][field])): + del request_init["tls_route"][field][i][subfield] + else: + del request_init["tls_route"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + + request = {} + client.update_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=gcn_tls_route.UpdateTlsRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + 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 + + response = client.update_tls_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("tlsRoute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tls_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_tls_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tls_route.UpdateTlsRouteRequest.pb(gcn_tls_route.UpdateTlsRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_tls_route.UpdateTlsRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tls_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tls_route.UpdateTlsRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_tls_route(request) + + +def test_update_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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 = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + tls_route=gcn_tls_route.TlsRoute(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 + + client.update_tls_route(**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/{tls_route.name=projects/*/locations/*/tlsRoutes/*}" % client.transport._host, args[1]) + + +def test_update_tls_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.UpdateTlsRouteRequest(), + tls_route=gcn_tls_route.TlsRoute(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tls_route.DeleteTlsRouteRequest, + dict, +]) +def test_delete_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_tls_route_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 = NetworkServicesClient( + 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_tls_route 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_tls_route] = mock_rpc + + request = {} + client.delete_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=tls_route.DeleteTlsRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_tls_route(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tls_route") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_tls_route") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.DeleteTlsRouteRequest.pb(tls_route.DeleteTlsRouteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tls_route.DeleteTlsRouteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tls_route_rest_bad_request(transport: str = 'rest', request_type=tls_route.DeleteTlsRouteRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_tls_route(request) + + +def test_delete_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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/tlsRoutes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, args[1]) + + +def test_delete_tls_route_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_tls_route( + tls_route.DeleteTlsRouteRequest(), + name='name_value', + ) + + +def test_delete_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service_binding.ListServiceBindingsRequest, + dict, +]) +def test_list_service_bindings_rest(request_type): + client = NetworkServicesClient( + 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 = service_binding.ListServiceBindingsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service_binding.ListServiceBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_service_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceBindingsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_service_bindings_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 = NetworkServicesClient( + 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_service_bindings 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_service_bindings] = mock_rpc + + request = {} + client.list_service_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_service_bindings(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_service_bindings_rest_required_fields(request_type=service_binding.ListServiceBindingsRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_service_bindings._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_service_bindings._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service_binding.ListServiceBindingsResponse() + # 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 = service_binding.ListServiceBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_service_bindings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_service_bindings_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_service_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_service_bindings_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_service_bindings") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_service_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.ListServiceBindingsRequest.pb(service_binding.ListServiceBindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_binding.ListServiceBindingsResponse.to_json(service_binding.ListServiceBindingsResponse()) + + request = service_binding.ListServiceBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_binding.ListServiceBindingsResponse() + + client.list_service_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_service_bindings_rest_bad_request(transport: str = 'rest', request_type=service_binding.ListServiceBindingsRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_service_bindings(request) + + +def test_list_service_bindings_rest_flattened(): + client = NetworkServicesClient( + 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 = service_binding.ListServiceBindingsResponse() + + # 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 = service_binding.ListServiceBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_service_bindings(**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/*}/serviceBindings" % client.transport._host, args[1]) + + +def test_list_service_bindings_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_service_bindings( + service_binding.ListServiceBindingsRequest(), + parent='parent_value', + ) + + +def test_list_service_bindings_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token='abc', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token='def', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token='ghi', + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service_binding.ListServiceBindingsResponse.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_service_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service_binding.ServiceBinding) + for i in results) + + pages = list(client.list_service_bindings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + service_binding.GetServiceBindingRequest, + dict, +]) +def test_get_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding( + name='name_value', + description='description_value', + service='service_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service_binding.ServiceBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_service_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_binding.ServiceBinding) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.service == 'service_value' + +def test_get_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + + request = {} + client.get_service_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_service_binding(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_service_binding_rest_required_fields(request_type=service_binding.GetServiceBindingRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_service_binding._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_service_binding._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service_binding.ServiceBinding() + # 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 = service_binding.ServiceBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_service_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_service_binding") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_service_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.GetServiceBindingRequest.pb(service_binding.GetServiceBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_binding.ServiceBinding.to_json(service_binding.ServiceBinding()) + + request = service_binding.GetServiceBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_binding.ServiceBinding() + + client.get_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_binding_rest_bad_request(transport: str = 'rest', request_type=service_binding.GetServiceBindingRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_service_binding(request) + + +def test_get_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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 = service_binding.ServiceBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_service_binding(**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/*/serviceBindings/*}" % client.transport._host, args[1]) + + +def test_get_service_binding_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_service_binding( + service_binding.GetServiceBindingRequest(), + name='name_value', + ) + + +def test_get_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_service_binding.CreateServiceBindingRequest, + dict, +]) +def test_create_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service_binding"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'service': 'service_value', 'labels': {}} + # 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_service_binding.CreateServiceBindingRequest.meta.fields["service_binding"] + + 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["service_binding"].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["service_binding"][field])): + del request_init["service_binding"][field][i][subfield] + else: + del request_init["service_binding"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_service_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + + request = {} + client.create_service_binding(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_service_binding(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_service_binding_rest_required_fields(request_type=gcn_service_binding.CreateServiceBindingRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_binding_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 "serviceBindingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceBindingId" in jsonified_request + assert jsonified_request["serviceBindingId"] == request_init["service_binding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["serviceBindingId"] = 'service_binding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("service_binding_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 "serviceBindingId" in jsonified_request + assert jsonified_request["serviceBindingId"] == 'service_binding_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_service_binding(request) + + expected_params = [ + ( + "serviceBindingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("serviceBindingId", )) & set(("parent", "serviceBindingId", "serviceBinding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_service_binding") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_service_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_service_binding.CreateServiceBindingRequest.pb(gcn_service_binding.CreateServiceBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_service_binding.CreateServiceBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_binding_rest_bad_request(transport: str = 'rest', request_type=gcn_service_binding.CreateServiceBindingRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_service_binding(request) + + +def test_create_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_service_binding(**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/*}/serviceBindings" % client.transport._host, args[1]) + + +def test_create_service_binding_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_service_binding( + gcn_service_binding.CreateServiceBindingRequest(), + parent='parent_value', + service_binding=gcn_service_binding.ServiceBinding(name='name_value'), + service_binding_id='service_binding_id_value', + ) + + +def test_create_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service_binding.DeleteServiceBindingRequest, + dict, +]) +def test_delete_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_service_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_service_binding_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 = NetworkServicesClient( + 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_service_binding 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_service_binding] = mock_rpc + + request = {} + client.delete_service_binding(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_service_binding(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_service_binding_rest_required_fields(request_type=service_binding.DeleteServiceBindingRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_service_binding._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_service_binding._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_service_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_service_binding") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_service_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.DeleteServiceBindingRequest.pb(service_binding.DeleteServiceBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service_binding.DeleteServiceBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_binding_rest_bad_request(transport: str = 'rest', request_type=service_binding.DeleteServiceBindingRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_service_binding(request) + + +def test_delete_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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/serviceBindings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_service_binding(**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/*/serviceBindings/*}" % client.transport._host, args[1]) + + +def test_delete_service_binding_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_service_binding( + service_binding.DeleteServiceBindingRequest(), + name='name_value', + ) + + +def test_delete_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + mesh.ListMeshesRequest, + dict, +]) +def test_list_meshes_rest(request_type): + client = NetworkServicesClient( + 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 = mesh.ListMeshesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mesh.ListMeshesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_meshes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeshesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_meshes_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 = NetworkServicesClient( + 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_meshes 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_meshes] = mock_rpc + + request = {} + client.list_meshes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_meshes(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_meshes_rest_required_fields(request_type=mesh.ListMeshesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_meshes._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_meshes._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mesh.ListMeshesResponse() + # 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 = mesh.ListMeshesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_meshes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_meshes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_meshes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_meshes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_meshes") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_meshes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.ListMeshesRequest.pb(mesh.ListMeshesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mesh.ListMeshesResponse.to_json(mesh.ListMeshesResponse()) + + request = mesh.ListMeshesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mesh.ListMeshesResponse() + + client.list_meshes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_meshes_rest_bad_request(transport: str = 'rest', request_type=mesh.ListMeshesRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_meshes(request) + + +def test_list_meshes_rest_flattened(): + client = NetworkServicesClient( + 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 = mesh.ListMeshesResponse() + + # 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 = mesh.ListMeshesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_meshes(**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/*}/meshes" % client.transport._host, args[1]) + + +def test_list_meshes_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_meshes( + mesh.ListMeshesRequest(), + parent='parent_value', + ) + + +def test_list_meshes_rest_pager(transport: str = 'rest'): + client = NetworkServicesClient( + 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 = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token='abc', + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token='def', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token='ghi', + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(mesh.ListMeshesResponse.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_meshes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mesh.Mesh) + for i in results) + + pages = list(client.list_meshes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + mesh.GetMeshRequest, + dict, +]) +def test_get_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/meshes/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 = mesh.Mesh( + name='name_value', + self_link='self_link_value', + description='description_value', + interception_port=1848, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mesh.Mesh.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_mesh(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mesh.Mesh) + assert response.name == 'name_value' + assert response.self_link == 'self_link_value' + assert response.description == 'description_value' + assert response.interception_port == 1848 + +def test_get_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + + request = {} + client.get_mesh(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mesh(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_mesh_rest_required_fields(request_type=mesh.GetMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mesh.Mesh() + # 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 = mesh.Mesh.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_mesh(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_mesh") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_mesh") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.GetMeshRequest.pb(mesh.GetMeshRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mesh.Mesh.to_json(mesh.Mesh()) + + request = mesh.GetMeshRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mesh.Mesh() + + client.get_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mesh_rest_bad_request(transport: str = 'rest', request_type=mesh.GetMeshRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mesh(request) + + +def test_get_mesh_rest_flattened(): + client = NetworkServicesClient( + 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 = mesh.Mesh() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/meshes/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 = mesh.Mesh.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_mesh(**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/*/meshes/*}" % client.transport._host, args[1]) + + +def test_get_mesh_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_mesh( + mesh.GetMeshRequest(), + name='name_value', + ) + + +def test_get_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_mesh.CreateMeshRequest, + dict, +]) +def test_create_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["mesh"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'interception_port': 1848} + # 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_mesh.CreateMeshRequest.meta.fields["mesh"] + + 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["mesh"].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["mesh"][field])): + del request_init["mesh"][field][i][subfield] + else: + del request_init["mesh"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + + request = {} + client.create_mesh(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_mesh(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_mesh_rest_required_fields(request_type=gcn_mesh.CreateMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mesh_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 "meshId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mesh._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "meshId" in jsonified_request + assert jsonified_request["meshId"] == request_init["mesh_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["meshId"] = 'mesh_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mesh._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mesh_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 "meshId" in jsonified_request + assert jsonified_request["meshId"] == 'mesh_id_value' + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_mesh(request) + + expected_params = [ + ( + "meshId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(("meshId", )) & set(("parent", "meshId", "mesh", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_mesh") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_mesh") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_mesh.CreateMeshRequest.pb(gcn_mesh.CreateMeshRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_mesh.CreateMeshRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mesh_rest_bad_request(transport: str = 'rest', request_type=gcn_mesh.CreateMeshRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mesh(request) + + +def test_create_mesh_rest_flattened(): + client = NetworkServicesClient( + 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', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_mesh(**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/*}/meshes" % client.transport._host, args[1]) + + +def test_create_mesh_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.CreateMeshRequest(), + parent='parent_value', + mesh=gcn_mesh.Mesh(name='name_value'), + mesh_id='mesh_id_value', + ) + + +def test_create_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_mesh.UpdateMeshRequest, + dict, +]) +def test_update_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} + request_init["mesh"] = {'name': 'projects/sample1/locations/sample2/meshes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'interception_port': 1848} + # 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_mesh.UpdateMeshRequest.meta.fields["mesh"] + + 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["mesh"].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["mesh"][field])): + del request_init["mesh"][field][i][subfield] + else: + del request_init["mesh"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + + request = {} + client.update_mesh(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_mesh(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_mesh_rest_required_fields(request_type=gcn_mesh.UpdateMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + 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 + + response = client.update_mesh(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("mesh", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_mesh") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_mesh") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_mesh.UpdateMeshRequest.pb(gcn_mesh.UpdateMeshRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = gcn_mesh.UpdateMeshRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mesh_rest_bad_request(transport: str = 'rest', request_type=gcn_mesh.UpdateMeshRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mesh(request) + + +def test_update_mesh_rest_flattened(): + client = NetworkServicesClient( + 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 = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + mesh=gcn_mesh.Mesh(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 + + client.update_mesh(**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/{mesh.name=projects/*/locations/*/meshes/*}" % client.transport._host, args[1]) + + +def test_update_mesh_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.UpdateMeshRequest(), + mesh=gcn_mesh.Mesh(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + mesh.DeleteMeshRequest, + dict, +]) +def test_delete_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_mesh_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 = NetworkServicesClient( + 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_mesh 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_mesh] = mock_rpc + + request = {} + client.delete_mesh(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_mesh(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_mesh_rest_required_fields(request_type=mesh.DeleteMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_mesh(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_mesh") as post, \ + mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_mesh") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.DeleteMeshRequest.pb(mesh.DeleteMeshRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = mesh.DeleteMeshRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_mesh_rest_bad_request(transport: str = 'rest', request_type=mesh.DeleteMeshRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mesh(request) + + +def test_delete_mesh_rest_flattened(): + client = NetworkServicesClient( + 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/meshes/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_mesh(**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/*/meshes/*}" % client.transport._host, args[1]) + + +def test_delete_mesh_rest_flattened_error(transport: str = 'rest'): + client = NetworkServicesClient( + 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_mesh( + mesh.DeleteMeshRequest(), + name='name_value', + ) + + +def test_delete_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkServicesClient( + 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 = NetworkServicesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkServicesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = NetworkServicesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkServicesGrpcTransport, + ) + +def test_network_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_network_services_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_services_v1.services.network_services.transports.NetworkServicesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_endpoint_policies', + 'get_endpoint_policy', + 'create_endpoint_policy', + 'update_endpoint_policy', + 'delete_endpoint_policy', + 'list_gateways', + 'get_gateway', + 'create_gateway', + 'update_gateway', + 'delete_gateway', + 'list_grpc_routes', + 'get_grpc_route', + 'create_grpc_route', + 'update_grpc_route', + 'delete_grpc_route', + 'list_http_routes', + 'get_http_route', + 'create_http_route', + 'update_http_route', + 'delete_http_route', + 'list_tcp_routes', + 'get_tcp_route', + 'create_tcp_route', + 'update_tcp_route', + 'delete_tcp_route', + 'list_tls_routes', + 'get_tls_route', + 'create_tls_route', + 'update_tls_route', + 'delete_tls_route', + 'list_service_bindings', + 'get_service_binding', + 'create_service_binding', + 'delete_service_binding', + 'list_meshes', + 'get_mesh', + 'create_mesh', + 'update_mesh', + 'delete_mesh', + '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_services_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_services_v1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkServicesTransport( + 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_services_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_services_v1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkServicesTransport() + adc.assert_called_once() + + +def test_network_services_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) + NetworkServicesClient() + 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.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + ], +) +def test_network_services_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.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, + ], +) +def test_network_services_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.NetworkServicesGrpcTransport, grpc_helpers), + (transports.NetworkServicesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_network_services_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( + "networkservices.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="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) +def test_network_services_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_services_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.NetworkServicesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_network_services_rest_lro_client(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_services_host_no_port(transport_name): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkservices.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkservices.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_services_host_with_port(transport_name): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networkservices.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networkservices.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_network_services_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkServicesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkServicesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_endpoint_policies._session + session2 = client2.transport.list_endpoint_policies._session + assert session1 != session2 + session1 = client1.transport.get_endpoint_policy._session + session2 = client2.transport.get_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.create_endpoint_policy._session + session2 = client2.transport.create_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.update_endpoint_policy._session + session2 = client2.transport.update_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.delete_endpoint_policy._session + session2 = client2.transport.delete_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.list_gateways._session + session2 = client2.transport.list_gateways._session + assert session1 != session2 + session1 = client1.transport.get_gateway._session + session2 = client2.transport.get_gateway._session + assert session1 != session2 + session1 = client1.transport.create_gateway._session + session2 = client2.transport.create_gateway._session + assert session1 != session2 + session1 = client1.transport.update_gateway._session + session2 = client2.transport.update_gateway._session + assert session1 != session2 + session1 = client1.transport.delete_gateway._session + session2 = client2.transport.delete_gateway._session + assert session1 != session2 + session1 = client1.transport.list_grpc_routes._session + session2 = client2.transport.list_grpc_routes._session + assert session1 != session2 + session1 = client1.transport.get_grpc_route._session + session2 = client2.transport.get_grpc_route._session + assert session1 != session2 + session1 = client1.transport.create_grpc_route._session + session2 = client2.transport.create_grpc_route._session + assert session1 != session2 + session1 = client1.transport.update_grpc_route._session + session2 = client2.transport.update_grpc_route._session + assert session1 != session2 + session1 = client1.transport.delete_grpc_route._session + session2 = client2.transport.delete_grpc_route._session + assert session1 != session2 + session1 = client1.transport.list_http_routes._session + session2 = client2.transport.list_http_routes._session + assert session1 != session2 + session1 = client1.transport.get_http_route._session + session2 = client2.transport.get_http_route._session + assert session1 != session2 + session1 = client1.transport.create_http_route._session + session2 = client2.transport.create_http_route._session + assert session1 != session2 + session1 = client1.transport.update_http_route._session + session2 = client2.transport.update_http_route._session + assert session1 != session2 + session1 = client1.transport.delete_http_route._session + session2 = client2.transport.delete_http_route._session + assert session1 != session2 + session1 = client1.transport.list_tcp_routes._session + session2 = client2.transport.list_tcp_routes._session + assert session1 != session2 + session1 = client1.transport.get_tcp_route._session + session2 = client2.transport.get_tcp_route._session + assert session1 != session2 + session1 = client1.transport.create_tcp_route._session + session2 = client2.transport.create_tcp_route._session + assert session1 != session2 + session1 = client1.transport.update_tcp_route._session + session2 = client2.transport.update_tcp_route._session + assert session1 != session2 + session1 = client1.transport.delete_tcp_route._session + session2 = client2.transport.delete_tcp_route._session + assert session1 != session2 + session1 = client1.transport.list_tls_routes._session + session2 = client2.transport.list_tls_routes._session + assert session1 != session2 + session1 = client1.transport.get_tls_route._session + session2 = client2.transport.get_tls_route._session + assert session1 != session2 + session1 = client1.transport.create_tls_route._session + session2 = client2.transport.create_tls_route._session + assert session1 != session2 + session1 = client1.transport.update_tls_route._session + session2 = client2.transport.update_tls_route._session + assert session1 != session2 + session1 = client1.transport.delete_tls_route._session + session2 = client2.transport.delete_tls_route._session + assert session1 != session2 + session1 = client1.transport.list_service_bindings._session + session2 = client2.transport.list_service_bindings._session + assert session1 != session2 + session1 = client1.transport.get_service_binding._session + session2 = client2.transport.get_service_binding._session + assert session1 != session2 + session1 = client1.transport.create_service_binding._session + session2 = client2.transport.create_service_binding._session + assert session1 != session2 + session1 = client1.transport.delete_service_binding._session + session2 = client2.transport.delete_service_binding._session + assert session1 != session2 + session1 = client1.transport.list_meshes._session + session2 = client2.transport.list_meshes._session + assert session1 != session2 + session1 = client1.transport.get_mesh._session + session2 = client2.transport.get_mesh._session + assert session1 != session2 + session1 = client1.transport.create_mesh._session + session2 = client2.transport.create_mesh._session + assert session1 != session2 + session1 = client1.transport.update_mesh._session + session2 = client2.transport.update_mesh._session + assert session1 != session2 + session1 = client1.transport.delete_mesh._session + session2 = client2.transport.delete_mesh._session + assert session1 != session2 +def test_network_services_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkServicesGrpcTransport( + 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_services_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkServicesGrpcAsyncIOTransport( + 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.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) +def test_network_services_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.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) +def test_network_services_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_services_grpc_lro_client(): + client = NetworkServicesClient( + 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_services_grpc_lro_async_client(): + client = NetworkServicesAsyncClient( + 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 = NetworkServicesClient.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 = NetworkServicesClient.authorization_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_authorization_policy_path(path) + assert expected == actual + +def test_backend_service_path(): + project = "cuttlefish" + location = "mussel" + backend_service = "winkle" + expected = "projects/{project}/locations/{location}/backendServices/{backend_service}".format(project=project, location=location, backend_service=backend_service, ) + actual = NetworkServicesClient.backend_service_path(project, location, backend_service) + assert expected == actual + + +def test_parse_backend_service_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "backend_service": "abalone", + } + path = NetworkServicesClient.backend_service_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_backend_service_path(path) + assert expected == actual + +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 = NetworkServicesClient.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 = NetworkServicesClient.client_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_client_tls_policy_path(path) + assert expected == actual + +def test_endpoint_policy_path(): + project = "cuttlefish" + location = "mussel" + endpoint_policy = "winkle" + expected = "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format(project=project, location=location, endpoint_policy=endpoint_policy, ) + actual = NetworkServicesClient.endpoint_policy_path(project, location, endpoint_policy) + assert expected == actual + + +def test_parse_endpoint_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "endpoint_policy": "abalone", + } + path = NetworkServicesClient.endpoint_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_endpoint_policy_path(path) + assert expected == actual + +def test_gateway_path(): + project = "squid" + location = "clam" + gateway = "whelk" + expected = "projects/{project}/locations/{location}/gateways/{gateway}".format(project=project, location=location, gateway=gateway, ) + actual = NetworkServicesClient.gateway_path(project, location, gateway) + assert expected == actual + + +def test_parse_gateway_path(): + expected = { + "project": "octopus", + "location": "oyster", + "gateway": "nudibranch", + } + path = NetworkServicesClient.gateway_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_gateway_path(path) + assert expected == actual + +def test_grpc_route_path(): + project = "cuttlefish" + location = "mussel" + grpc_route = "winkle" + expected = "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format(project=project, location=location, grpc_route=grpc_route, ) + actual = NetworkServicesClient.grpc_route_path(project, location, grpc_route) + assert expected == actual + + +def test_parse_grpc_route_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "grpc_route": "abalone", + } + path = NetworkServicesClient.grpc_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_grpc_route_path(path) + assert expected == actual + +def test_http_route_path(): + project = "squid" + location = "clam" + http_route = "whelk" + expected = "projects/{project}/locations/{location}/httpRoutes/{http_route}".format(project=project, location=location, http_route=http_route, ) + actual = NetworkServicesClient.http_route_path(project, location, http_route) + assert expected == actual + + +def test_parse_http_route_path(): + expected = { + "project": "octopus", + "location": "oyster", + "http_route": "nudibranch", + } + path = NetworkServicesClient.http_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_http_route_path(path) + assert expected == actual + +def test_mesh_path(): + project = "cuttlefish" + location = "mussel" + mesh = "winkle" + expected = "projects/{project}/locations/{location}/meshes/{mesh}".format(project=project, location=location, mesh=mesh, ) + actual = NetworkServicesClient.mesh_path(project, location, mesh) + assert expected == actual + + +def test_parse_mesh_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "mesh": "abalone", + } + path = NetworkServicesClient.mesh_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_mesh_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 = NetworkServicesClient.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 = NetworkServicesClient.server_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_server_tls_policy_path(path) + assert expected == actual + +def test_service_binding_path(): + project = "cuttlefish" + location = "mussel" + service_binding = "winkle" + expected = "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format(project=project, location=location, service_binding=service_binding, ) + actual = NetworkServicesClient.service_binding_path(project, location, service_binding) + assert expected == actual + + +def test_parse_service_binding_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "service_binding": "abalone", + } + path = NetworkServicesClient.service_binding_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_service_binding_path(path) + assert expected == actual + +def test_tcp_route_path(): + project = "squid" + location = "clam" + tcp_route = "whelk" + expected = "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format(project=project, location=location, tcp_route=tcp_route, ) + actual = NetworkServicesClient.tcp_route_path(project, location, tcp_route) + assert expected == actual + + +def test_parse_tcp_route_path(): + expected = { + "project": "octopus", + "location": "oyster", + "tcp_route": "nudibranch", + } + path = NetworkServicesClient.tcp_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_tcp_route_path(path) + assert expected == actual + +def test_tls_route_path(): + project = "cuttlefish" + location = "mussel" + tls_route = "winkle" + expected = "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format(project=project, location=location, tls_route=tls_route, ) + actual = NetworkServicesClient.tls_route_path(project, location, tls_route) + assert expected == actual + + +def test_parse_tls_route_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "tls_route": "abalone", + } + path = NetworkServicesClient.tls_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_tls_route_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = NetworkServicesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = NetworkServicesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = NetworkServicesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = NetworkServicesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = NetworkServicesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = NetworkServicesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = NetworkServicesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = NetworkServicesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = NetworkServicesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = NetworkServicesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.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.NetworkServicesTransport, '_prep_wrapped_messages') as prep: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.NetworkServicesTransport, '_prep_wrapped_messages') as prep: + transport_class = NetworkServicesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = NetworkServicesClient( + 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 = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = NetworkServicesClient( + 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", [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport), +]) +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 3b489c3bdea3d80ec2a361bdb8ae0cd5ec4533d7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 31 May 2024 10:59:55 +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-services/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../docs/network_services_v1/dep_service.rst | 10 - .../network_services_v1/network_services.rst | 10 - .../v1/docs/network_services_v1/services_.rst | 7 - .../v1/docs/network_services_v1/types_.rst | 6 - .../google/cloud/network_services/__init__.py | 181 - .../cloud/network_services/gapic_version.py | 16 - .../v1/google/cloud/network_services/py.typed | 2 - .../cloud/network_services_v1/__init__.py | 182 - .../network_services_v1/gapic_metadata.json | 782 - .../network_services_v1/gapic_version.py | 16 - .../google/cloud/network_services_v1/py.typed | 2 - .../network_services_v1/services/__init__.py | 15 - .../services/dep_service/__init__.py | 22 - .../services/dep_service/async_client.py | 2148 -- .../services/dep_service/client.py | 2498 -- .../services/dep_service/pagers.py | 260 - .../dep_service/transports/__init__.py | 38 - .../services/dep_service/transports/base.py | 370 - .../services/dep_service/transports/grpc.py | 718 - .../dep_service/transports/grpc_asyncio.py | 773 - .../services/dep_service/transports/rest.py | 2226 -- .../services/network_services/__init__.py | 22 - .../services/network_services/async_client.py | 5791 --- .../services/network_services/client.py | 6202 --- .../services/network_services/pagers.py | 993 - .../network_services/transports/__init__.py | 38 - .../network_services/transports/base.py | 791 - .../network_services/transports/grpc.py | 1487 - .../transports/grpc_asyncio.py | 1687 - .../network_services/transports/rest.py | 5574 --- .../network_services_v1/types/__init__.py | 188 - .../cloud/network_services_v1/types/common.py | 227 - .../cloud/network_services_v1/types/dep.py | 945 - .../types/endpoint_policy.py | 317 - .../network_services_v1/types/gateway.py | 305 - .../network_services_v1/types/grpc_route.py | 719 - .../network_services_v1/types/http_route.py | 1125 - .../cloud/network_services_v1/types/mesh.py | 255 - .../types/network_services.py | 26 - .../types/service_binding.py | 215 - .../network_services_v1/types/tcp_route.py | 405 - .../network_services_v1/types/tls_route.py | 366 - .../google-cloud-network-services/v1/mypy.ini | 3 - .../v1/noxfile.py | 253 - ...service_create_lb_route_extension_async.py | 67 - ..._service_create_lb_route_extension_sync.py | 67 - ...rvice_create_lb_traffic_extension_async.py | 67 - ...ervice_create_lb_traffic_extension_sync.py | 67 - ...service_delete_lb_route_extension_async.py | 56 - ..._service_delete_lb_route_extension_sync.py | 56 - ...rvice_delete_lb_traffic_extension_async.py | 56 - ...ervice_delete_lb_traffic_extension_sync.py | 56 - ...ep_service_get_lb_route_extension_async.py | 52 - ...dep_service_get_lb_route_extension_sync.py | 52 - ..._service_get_lb_traffic_extension_async.py | 52 - ...p_service_get_lb_traffic_extension_sync.py | 52 - ..._service_list_lb_route_extensions_async.py | 53 - ...p_service_list_lb_route_extensions_sync.py | 53 - ...ervice_list_lb_traffic_extensions_async.py | 53 - ...service_list_lb_traffic_extensions_sync.py | 53 - ...service_update_lb_route_extension_async.py | 65 - ..._service_update_lb_route_extension_sync.py | 65 - ...rvice_update_lb_traffic_extension_async.py | 65 - ...ervice_update_lb_traffic_extension_sync.py | 65 - ...k_services_create_endpoint_policy_async.py | 62 - ...rk_services_create_endpoint_policy_sync.py | 62 - ...d_network_services_create_gateway_async.py | 63 - ...ed_network_services_create_gateway_sync.py | 63 - ...etwork_services_create_grpc_route_async.py | 62 - ...network_services_create_grpc_route_sync.py | 62 - ...etwork_services_create_http_route_async.py | 62 - ...network_services_create_http_route_sync.py | 62 - ...ated_network_services_create_mesh_async.py | 61 - ...rated_network_services_create_mesh_sync.py | 61 - ...k_services_create_service_binding_async.py | 62 - ...rk_services_create_service_binding_sync.py | 62 - ...network_services_create_tcp_route_async.py | 61 - ..._network_services_create_tcp_route_sync.py | 61 - ...network_services_create_tls_route_async.py | 62 - ..._network_services_create_tls_route_sync.py | 62 - ...k_services_delete_endpoint_policy_async.py | 56 - ...rk_services_delete_endpoint_policy_sync.py | 56 - ...d_network_services_delete_gateway_async.py | 56 - ...ed_network_services_delete_gateway_sync.py | 56 - ...etwork_services_delete_grpc_route_async.py | 56 - ...network_services_delete_grpc_route_sync.py | 56 - ...etwork_services_delete_http_route_async.py | 56 - ...network_services_delete_http_route_sync.py | 56 - ...ated_network_services_delete_mesh_async.py | 56 - ...rated_network_services_delete_mesh_sync.py | 56 - ...k_services_delete_service_binding_async.py | 56 - ...rk_services_delete_service_binding_sync.py | 56 - ...network_services_delete_tcp_route_async.py | 56 - ..._network_services_delete_tcp_route_sync.py | 56 - ...network_services_delete_tls_route_async.py | 56 - ..._network_services_delete_tls_route_sync.py | 56 - ...work_services_get_endpoint_policy_async.py | 52 - ...twork_services_get_endpoint_policy_sync.py | 52 - ...ated_network_services_get_gateway_async.py | 52 - ...rated_network_services_get_gateway_sync.py | 52 - ...d_network_services_get_grpc_route_async.py | 52 - ...ed_network_services_get_grpc_route_sync.py | 52 - ...d_network_services_get_http_route_async.py | 52 - ...ed_network_services_get_http_route_sync.py | 52 - ...nerated_network_services_get_mesh_async.py | 52 - ...enerated_network_services_get_mesh_sync.py | 52 - ...work_services_get_service_binding_async.py | 52 - ...twork_services_get_service_binding_sync.py | 52 - ...ed_network_services_get_tcp_route_async.py | 52 - ...ted_network_services_get_tcp_route_sync.py | 52 - ...ed_network_services_get_tls_route_async.py | 52 - ...ted_network_services_get_tls_route_sync.py | 52 - ...k_services_list_endpoint_policies_async.py | 53 - ...rk_services_list_endpoint_policies_sync.py | 53 - ...ed_network_services_list_gateways_async.py | 53 - ...ted_network_services_list_gateways_sync.py | 53 - ...network_services_list_grpc_routes_async.py | 53 - ..._network_services_list_grpc_routes_sync.py | 53 - ...network_services_list_http_routes_async.py | 53 - ..._network_services_list_http_routes_sync.py | 53 - ...ated_network_services_list_meshes_async.py | 53 - ...rated_network_services_list_meshes_sync.py | 53 - ...rk_services_list_service_bindings_async.py | 53 - ...ork_services_list_service_bindings_sync.py | 53 - ..._network_services_list_tcp_routes_async.py | 53 - ...d_network_services_list_tcp_routes_sync.py | 53 - ..._network_services_list_tls_routes_async.py | 53 - ...d_network_services_list_tls_routes_sync.py | 53 - ...k_services_update_endpoint_policy_async.py | 60 - ...rk_services_update_endpoint_policy_sync.py | 60 - ...d_network_services_update_gateway_async.py | 61 - ...ed_network_services_update_gateway_sync.py | 61 - ...etwork_services_update_grpc_route_async.py | 60 - ...network_services_update_grpc_route_sync.py | 60 - ...etwork_services_update_http_route_async.py | 60 - ...network_services_update_http_route_sync.py | 60 - ...ated_network_services_update_mesh_async.py | 59 - ...rated_network_services_update_mesh_sync.py | 59 - ...network_services_update_tcp_route_async.py | 59 - ..._network_services_update_tcp_route_sync.py | 59 - ...network_services_update_tls_route_async.py | 60 - ..._network_services_update_tls_route_sync.py | 60 - ...adata_google.cloud.networkservices.v1.json | 8136 ---- .../fixup_network_services_v1_keywords.py | 224 - .../google-cloud-network-services/v1/setup.py | 94 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 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_services_v1/__init__.py | 16 - .../network_services_v1/test_dep_service.py | 10386 ----- .../test_network_services.py | 31441 ---------------- .../services/dep_service/async_client.py | 5 +- .../services/dep_service/client.py | 5 +- .../services/dep_service/transports/rest.py | 8 +- .../cloud/network_services_v1/types/dep.py | 39 +- .../fixup_network_services_v1_keywords.py | 4 +- .../network_services_v1/test_dep_service.py | 19 +- 170 files changed, 52 insertions(+), 94694 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py delete mode 100644 owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/.coveragerc b/owl-bot-staging/google-cloud-network-services/v1/.coveragerc deleted file mode 100644 index 778e27d73587..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_services/__init__.py - google/cloud/network_services/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-services/v1/.flake8 b/owl-bot-staging/google-cloud-network-services/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in deleted file mode 100644 index 75e280b90bde..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/network_services *.py -recursive-include google/cloud/network_services_v1 *.py diff --git a/owl-bot-staging/google-cloud-network-services/v1/README.rst b/owl-bot-staging/google-cloud-network-services/v1/README.rst deleted file mode 100644 index afbddfa3288a..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Network Services 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 Services API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py deleted file mode 100644 index dc71e2abe004..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-services" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-network-services-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-services.tex", - u"google-cloud-network-services 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-services", - u"Google Cloud Network Services 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-services", - u"google-cloud-network-services Documentation", - author, - "google-cloud-network-services", - "GAPIC library for Google Cloud Network Services API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst deleted file mode 100644 index 5975c3816b2b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_services_v1/services - network_services_v1/types diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst deleted file mode 100644 index b6844727e4f7..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/dep_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DepService ----------------------------- - -.. automodule:: google.cloud.network_services_v1.services.dep_service - :members: - :inherited-members: - -.. automodule:: google.cloud.network_services_v1.services.dep_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst deleted file mode 100644 index 29ec7184b84c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/network_services.rst +++ /dev/null @@ -1,10 +0,0 @@ -NetworkServices ---------------------------------- - -.. automodule:: google.cloud.network_services_v1.services.network_services - :members: - :inherited-members: - -.. automodule:: google.cloud.network_services_v1.services.network_services.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst deleted file mode 100644 index ca8a37c10d65..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Network Services v1 API -================================================= -.. toctree:: - :maxdepth: 2 - - dep_service - network_services diff --git a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst b/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst deleted file mode 100644 index 5706e60c91b7..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/docs/network_services_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Services v1 API -============================================== - -.. automodule:: google.cloud.network_services_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py deleted file mode 100644 index 49d70c891e5c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/__init__.py +++ /dev/null @@ -1,181 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_services import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_services_v1.services.dep_service.client import DepServiceClient -from google.cloud.network_services_v1.services.dep_service.async_client import DepServiceAsyncClient -from google.cloud.network_services_v1.services.network_services.client import NetworkServicesClient -from google.cloud.network_services_v1.services.network_services.async_client import NetworkServicesAsyncClient - -from google.cloud.network_services_v1.types.common import EndpointMatcher -from google.cloud.network_services_v1.types.common import OperationMetadata -from google.cloud.network_services_v1.types.common import TrafficPortSelector -from google.cloud.network_services_v1.types.dep import CreateLbRouteExtensionRequest -from google.cloud.network_services_v1.types.dep import CreateLbTrafficExtensionRequest -from google.cloud.network_services_v1.types.dep import DeleteLbRouteExtensionRequest -from google.cloud.network_services_v1.types.dep import DeleteLbTrafficExtensionRequest -from google.cloud.network_services_v1.types.dep import ExtensionChain -from google.cloud.network_services_v1.types.dep import GetLbRouteExtensionRequest -from google.cloud.network_services_v1.types.dep import GetLbTrafficExtensionRequest -from google.cloud.network_services_v1.types.dep import LbRouteExtension -from google.cloud.network_services_v1.types.dep import LbTrafficExtension -from google.cloud.network_services_v1.types.dep import ListLbRouteExtensionsRequest -from google.cloud.network_services_v1.types.dep import ListLbRouteExtensionsResponse -from google.cloud.network_services_v1.types.dep import ListLbTrafficExtensionsRequest -from google.cloud.network_services_v1.types.dep import ListLbTrafficExtensionsResponse -from google.cloud.network_services_v1.types.dep import UpdateLbRouteExtensionRequest -from google.cloud.network_services_v1.types.dep import UpdateLbTrafficExtensionRequest -from google.cloud.network_services_v1.types.dep import EventType -from google.cloud.network_services_v1.types.dep import LoadBalancingScheme -from google.cloud.network_services_v1.types.endpoint_policy import CreateEndpointPolicyRequest -from google.cloud.network_services_v1.types.endpoint_policy import DeleteEndpointPolicyRequest -from google.cloud.network_services_v1.types.endpoint_policy import EndpointPolicy -from google.cloud.network_services_v1.types.endpoint_policy import GetEndpointPolicyRequest -from google.cloud.network_services_v1.types.endpoint_policy import ListEndpointPoliciesRequest -from google.cloud.network_services_v1.types.endpoint_policy import ListEndpointPoliciesResponse -from google.cloud.network_services_v1.types.endpoint_policy import UpdateEndpointPolicyRequest -from google.cloud.network_services_v1.types.gateway import CreateGatewayRequest -from google.cloud.network_services_v1.types.gateway import DeleteGatewayRequest -from google.cloud.network_services_v1.types.gateway import Gateway -from google.cloud.network_services_v1.types.gateway import GetGatewayRequest -from google.cloud.network_services_v1.types.gateway import ListGatewaysRequest -from google.cloud.network_services_v1.types.gateway import ListGatewaysResponse -from google.cloud.network_services_v1.types.gateway import UpdateGatewayRequest -from google.cloud.network_services_v1.types.grpc_route import CreateGrpcRouteRequest -from google.cloud.network_services_v1.types.grpc_route import DeleteGrpcRouteRequest -from google.cloud.network_services_v1.types.grpc_route import GetGrpcRouteRequest -from google.cloud.network_services_v1.types.grpc_route import GrpcRoute -from google.cloud.network_services_v1.types.grpc_route import ListGrpcRoutesRequest -from google.cloud.network_services_v1.types.grpc_route import ListGrpcRoutesResponse -from google.cloud.network_services_v1.types.grpc_route import UpdateGrpcRouteRequest -from google.cloud.network_services_v1.types.http_route import CreateHttpRouteRequest -from google.cloud.network_services_v1.types.http_route import DeleteHttpRouteRequest -from google.cloud.network_services_v1.types.http_route import GetHttpRouteRequest -from google.cloud.network_services_v1.types.http_route import HttpRoute -from google.cloud.network_services_v1.types.http_route import ListHttpRoutesRequest -from google.cloud.network_services_v1.types.http_route import ListHttpRoutesResponse -from google.cloud.network_services_v1.types.http_route import UpdateHttpRouteRequest -from google.cloud.network_services_v1.types.mesh import CreateMeshRequest -from google.cloud.network_services_v1.types.mesh import DeleteMeshRequest -from google.cloud.network_services_v1.types.mesh import GetMeshRequest -from google.cloud.network_services_v1.types.mesh import ListMeshesRequest -from google.cloud.network_services_v1.types.mesh import ListMeshesResponse -from google.cloud.network_services_v1.types.mesh import Mesh -from google.cloud.network_services_v1.types.mesh import UpdateMeshRequest -from google.cloud.network_services_v1.types.service_binding import CreateServiceBindingRequest -from google.cloud.network_services_v1.types.service_binding import DeleteServiceBindingRequest -from google.cloud.network_services_v1.types.service_binding import GetServiceBindingRequest -from google.cloud.network_services_v1.types.service_binding import ListServiceBindingsRequest -from google.cloud.network_services_v1.types.service_binding import ListServiceBindingsResponse -from google.cloud.network_services_v1.types.service_binding import ServiceBinding -from google.cloud.network_services_v1.types.tcp_route import CreateTcpRouteRequest -from google.cloud.network_services_v1.types.tcp_route import DeleteTcpRouteRequest -from google.cloud.network_services_v1.types.tcp_route import GetTcpRouteRequest -from google.cloud.network_services_v1.types.tcp_route import ListTcpRoutesRequest -from google.cloud.network_services_v1.types.tcp_route import ListTcpRoutesResponse -from google.cloud.network_services_v1.types.tcp_route import TcpRoute -from google.cloud.network_services_v1.types.tcp_route import UpdateTcpRouteRequest -from google.cloud.network_services_v1.types.tls_route import CreateTlsRouteRequest -from google.cloud.network_services_v1.types.tls_route import DeleteTlsRouteRequest -from google.cloud.network_services_v1.types.tls_route import GetTlsRouteRequest -from google.cloud.network_services_v1.types.tls_route import ListTlsRoutesRequest -from google.cloud.network_services_v1.types.tls_route import ListTlsRoutesResponse -from google.cloud.network_services_v1.types.tls_route import TlsRoute -from google.cloud.network_services_v1.types.tls_route import UpdateTlsRouteRequest - -__all__ = ('DepServiceClient', - 'DepServiceAsyncClient', - 'NetworkServicesClient', - 'NetworkServicesAsyncClient', - 'EndpointMatcher', - 'OperationMetadata', - 'TrafficPortSelector', - 'CreateLbRouteExtensionRequest', - 'CreateLbTrafficExtensionRequest', - 'DeleteLbRouteExtensionRequest', - 'DeleteLbTrafficExtensionRequest', - 'ExtensionChain', - 'GetLbRouteExtensionRequest', - 'GetLbTrafficExtensionRequest', - 'LbRouteExtension', - 'LbTrafficExtension', - 'ListLbRouteExtensionsRequest', - 'ListLbRouteExtensionsResponse', - 'ListLbTrafficExtensionsRequest', - 'ListLbTrafficExtensionsResponse', - 'UpdateLbRouteExtensionRequest', - 'UpdateLbTrafficExtensionRequest', - 'EventType', - 'LoadBalancingScheme', - 'CreateEndpointPolicyRequest', - 'DeleteEndpointPolicyRequest', - 'EndpointPolicy', - 'GetEndpointPolicyRequest', - 'ListEndpointPoliciesRequest', - 'ListEndpointPoliciesResponse', - 'UpdateEndpointPolicyRequest', - 'CreateGatewayRequest', - 'DeleteGatewayRequest', - 'Gateway', - 'GetGatewayRequest', - 'ListGatewaysRequest', - 'ListGatewaysResponse', - 'UpdateGatewayRequest', - 'CreateGrpcRouteRequest', - 'DeleteGrpcRouteRequest', - 'GetGrpcRouteRequest', - 'GrpcRoute', - 'ListGrpcRoutesRequest', - 'ListGrpcRoutesResponse', - 'UpdateGrpcRouteRequest', - 'CreateHttpRouteRequest', - 'DeleteHttpRouteRequest', - 'GetHttpRouteRequest', - 'HttpRoute', - 'ListHttpRoutesRequest', - 'ListHttpRoutesResponse', - 'UpdateHttpRouteRequest', - 'CreateMeshRequest', - 'DeleteMeshRequest', - 'GetMeshRequest', - 'ListMeshesRequest', - 'ListMeshesResponse', - 'Mesh', - 'UpdateMeshRequest', - 'CreateServiceBindingRequest', - 'DeleteServiceBindingRequest', - 'GetServiceBindingRequest', - 'ListServiceBindingsRequest', - 'ListServiceBindingsResponse', - 'ServiceBinding', - 'CreateTcpRouteRequest', - 'DeleteTcpRouteRequest', - 'GetTcpRouteRequest', - 'ListTcpRoutesRequest', - 'ListTcpRoutesResponse', - 'TcpRoute', - 'UpdateTcpRouteRequest', - 'CreateTlsRouteRequest', - 'DeleteTlsRouteRequest', - 'GetTlsRouteRequest', - 'ListTlsRoutesRequest', - 'ListTlsRoutesResponse', - 'TlsRoute', - 'UpdateTlsRouteRequest', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/google/cloud/network_services/py.typed b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed deleted file mode 100644 index dfe9bf70b7d5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-services package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py deleted file mode 100644 index 3eff2a66dbaa..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/__init__.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_services_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.dep_service import DepServiceClient -from .services.dep_service import DepServiceAsyncClient -from .services.network_services import NetworkServicesClient -from .services.network_services import NetworkServicesAsyncClient - -from .types.common import EndpointMatcher -from .types.common import OperationMetadata -from .types.common import TrafficPortSelector -from .types.dep import CreateLbRouteExtensionRequest -from .types.dep import CreateLbTrafficExtensionRequest -from .types.dep import DeleteLbRouteExtensionRequest -from .types.dep import DeleteLbTrafficExtensionRequest -from .types.dep import ExtensionChain -from .types.dep import GetLbRouteExtensionRequest -from .types.dep import GetLbTrafficExtensionRequest -from .types.dep import LbRouteExtension -from .types.dep import LbTrafficExtension -from .types.dep import ListLbRouteExtensionsRequest -from .types.dep import ListLbRouteExtensionsResponse -from .types.dep import ListLbTrafficExtensionsRequest -from .types.dep import ListLbTrafficExtensionsResponse -from .types.dep import UpdateLbRouteExtensionRequest -from .types.dep import UpdateLbTrafficExtensionRequest -from .types.dep import EventType -from .types.dep import LoadBalancingScheme -from .types.endpoint_policy import CreateEndpointPolicyRequest -from .types.endpoint_policy import DeleteEndpointPolicyRequest -from .types.endpoint_policy import EndpointPolicy -from .types.endpoint_policy import GetEndpointPolicyRequest -from .types.endpoint_policy import ListEndpointPoliciesRequest -from .types.endpoint_policy import ListEndpointPoliciesResponse -from .types.endpoint_policy import UpdateEndpointPolicyRequest -from .types.gateway import CreateGatewayRequest -from .types.gateway import DeleteGatewayRequest -from .types.gateway import Gateway -from .types.gateway import GetGatewayRequest -from .types.gateway import ListGatewaysRequest -from .types.gateway import ListGatewaysResponse -from .types.gateway import UpdateGatewayRequest -from .types.grpc_route import CreateGrpcRouteRequest -from .types.grpc_route import DeleteGrpcRouteRequest -from .types.grpc_route import GetGrpcRouteRequest -from .types.grpc_route import GrpcRoute -from .types.grpc_route import ListGrpcRoutesRequest -from .types.grpc_route import ListGrpcRoutesResponse -from .types.grpc_route import UpdateGrpcRouteRequest -from .types.http_route import CreateHttpRouteRequest -from .types.http_route import DeleteHttpRouteRequest -from .types.http_route import GetHttpRouteRequest -from .types.http_route import HttpRoute -from .types.http_route import ListHttpRoutesRequest -from .types.http_route import ListHttpRoutesResponse -from .types.http_route import UpdateHttpRouteRequest -from .types.mesh import CreateMeshRequest -from .types.mesh import DeleteMeshRequest -from .types.mesh import GetMeshRequest -from .types.mesh import ListMeshesRequest -from .types.mesh import ListMeshesResponse -from .types.mesh import Mesh -from .types.mesh import UpdateMeshRequest -from .types.service_binding import CreateServiceBindingRequest -from .types.service_binding import DeleteServiceBindingRequest -from .types.service_binding import GetServiceBindingRequest -from .types.service_binding import ListServiceBindingsRequest -from .types.service_binding import ListServiceBindingsResponse -from .types.service_binding import ServiceBinding -from .types.tcp_route import CreateTcpRouteRequest -from .types.tcp_route import DeleteTcpRouteRequest -from .types.tcp_route import GetTcpRouteRequest -from .types.tcp_route import ListTcpRoutesRequest -from .types.tcp_route import ListTcpRoutesResponse -from .types.tcp_route import TcpRoute -from .types.tcp_route import UpdateTcpRouteRequest -from .types.tls_route import CreateTlsRouteRequest -from .types.tls_route import DeleteTlsRouteRequest -from .types.tls_route import GetTlsRouteRequest -from .types.tls_route import ListTlsRoutesRequest -from .types.tls_route import ListTlsRoutesResponse -from .types.tls_route import TlsRoute -from .types.tls_route import UpdateTlsRouteRequest - -__all__ = ( - 'DepServiceAsyncClient', - 'NetworkServicesAsyncClient', -'CreateEndpointPolicyRequest', -'CreateGatewayRequest', -'CreateGrpcRouteRequest', -'CreateHttpRouteRequest', -'CreateLbRouteExtensionRequest', -'CreateLbTrafficExtensionRequest', -'CreateMeshRequest', -'CreateServiceBindingRequest', -'CreateTcpRouteRequest', -'CreateTlsRouteRequest', -'DeleteEndpointPolicyRequest', -'DeleteGatewayRequest', -'DeleteGrpcRouteRequest', -'DeleteHttpRouteRequest', -'DeleteLbRouteExtensionRequest', -'DeleteLbTrafficExtensionRequest', -'DeleteMeshRequest', -'DeleteServiceBindingRequest', -'DeleteTcpRouteRequest', -'DeleteTlsRouteRequest', -'DepServiceClient', -'EndpointMatcher', -'EndpointPolicy', -'EventType', -'ExtensionChain', -'Gateway', -'GetEndpointPolicyRequest', -'GetGatewayRequest', -'GetGrpcRouteRequest', -'GetHttpRouteRequest', -'GetLbRouteExtensionRequest', -'GetLbTrafficExtensionRequest', -'GetMeshRequest', -'GetServiceBindingRequest', -'GetTcpRouteRequest', -'GetTlsRouteRequest', -'GrpcRoute', -'HttpRoute', -'LbRouteExtension', -'LbTrafficExtension', -'ListEndpointPoliciesRequest', -'ListEndpointPoliciesResponse', -'ListGatewaysRequest', -'ListGatewaysResponse', -'ListGrpcRoutesRequest', -'ListGrpcRoutesResponse', -'ListHttpRoutesRequest', -'ListHttpRoutesResponse', -'ListLbRouteExtensionsRequest', -'ListLbRouteExtensionsResponse', -'ListLbTrafficExtensionsRequest', -'ListLbTrafficExtensionsResponse', -'ListMeshesRequest', -'ListMeshesResponse', -'ListServiceBindingsRequest', -'ListServiceBindingsResponse', -'ListTcpRoutesRequest', -'ListTcpRoutesResponse', -'ListTlsRoutesRequest', -'ListTlsRoutesResponse', -'LoadBalancingScheme', -'Mesh', -'NetworkServicesClient', -'OperationMetadata', -'ServiceBinding', -'TcpRoute', -'TlsRoute', -'TrafficPortSelector', -'UpdateEndpointPolicyRequest', -'UpdateGatewayRequest', -'UpdateGrpcRouteRequest', -'UpdateHttpRouteRequest', -'UpdateLbRouteExtensionRequest', -'UpdateLbTrafficExtensionRequest', -'UpdateMeshRequest', -'UpdateTcpRouteRequest', -'UpdateTlsRouteRequest', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json deleted file mode 100644 index 0c8a6247dfc9..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_metadata.json +++ /dev/null @@ -1,782 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_services_v1", - "protoPackage": "google.cloud.networkservices.v1", - "schema": "1.0", - "services": { - "DepService": { - "clients": { - "grpc": { - "libraryClient": "DepServiceClient", - "rpcs": { - "CreateLbRouteExtension": { - "methods": [ - "create_lb_route_extension" - ] - }, - "CreateLbTrafficExtension": { - "methods": [ - "create_lb_traffic_extension" - ] - }, - "DeleteLbRouteExtension": { - "methods": [ - "delete_lb_route_extension" - ] - }, - "DeleteLbTrafficExtension": { - "methods": [ - "delete_lb_traffic_extension" - ] - }, - "GetLbRouteExtension": { - "methods": [ - "get_lb_route_extension" - ] - }, - "GetLbTrafficExtension": { - "methods": [ - "get_lb_traffic_extension" - ] - }, - "ListLbRouteExtensions": { - "methods": [ - "list_lb_route_extensions" - ] - }, - "ListLbTrafficExtensions": { - "methods": [ - "list_lb_traffic_extensions" - ] - }, - "UpdateLbRouteExtension": { - "methods": [ - "update_lb_route_extension" - ] - }, - "UpdateLbTrafficExtension": { - "methods": [ - "update_lb_traffic_extension" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DepServiceAsyncClient", - "rpcs": { - "CreateLbRouteExtension": { - "methods": [ - "create_lb_route_extension" - ] - }, - "CreateLbTrafficExtension": { - "methods": [ - "create_lb_traffic_extension" - ] - }, - "DeleteLbRouteExtension": { - "methods": [ - "delete_lb_route_extension" - ] - }, - "DeleteLbTrafficExtension": { - "methods": [ - "delete_lb_traffic_extension" - ] - }, - "GetLbRouteExtension": { - "methods": [ - "get_lb_route_extension" - ] - }, - "GetLbTrafficExtension": { - "methods": [ - "get_lb_traffic_extension" - ] - }, - "ListLbRouteExtensions": { - "methods": [ - "list_lb_route_extensions" - ] - }, - "ListLbTrafficExtensions": { - "methods": [ - "list_lb_traffic_extensions" - ] - }, - "UpdateLbRouteExtension": { - "methods": [ - "update_lb_route_extension" - ] - }, - "UpdateLbTrafficExtension": { - "methods": [ - "update_lb_traffic_extension" - ] - } - } - }, - "rest": { - "libraryClient": "DepServiceClient", - "rpcs": { - "CreateLbRouteExtension": { - "methods": [ - "create_lb_route_extension" - ] - }, - "CreateLbTrafficExtension": { - "methods": [ - "create_lb_traffic_extension" - ] - }, - "DeleteLbRouteExtension": { - "methods": [ - "delete_lb_route_extension" - ] - }, - "DeleteLbTrafficExtension": { - "methods": [ - "delete_lb_traffic_extension" - ] - }, - "GetLbRouteExtension": { - "methods": [ - "get_lb_route_extension" - ] - }, - "GetLbTrafficExtension": { - "methods": [ - "get_lb_traffic_extension" - ] - }, - "ListLbRouteExtensions": { - "methods": [ - "list_lb_route_extensions" - ] - }, - "ListLbTrafficExtensions": { - "methods": [ - "list_lb_traffic_extensions" - ] - }, - "UpdateLbRouteExtension": { - "methods": [ - "update_lb_route_extension" - ] - }, - "UpdateLbTrafficExtension": { - "methods": [ - "update_lb_traffic_extension" - ] - } - } - } - } - }, - "NetworkServices": { - "clients": { - "grpc": { - "libraryClient": "NetworkServicesClient", - "rpcs": { - "CreateEndpointPolicy": { - "methods": [ - "create_endpoint_policy" - ] - }, - "CreateGateway": { - "methods": [ - "create_gateway" - ] - }, - "CreateGrpcRoute": { - "methods": [ - "create_grpc_route" - ] - }, - "CreateHttpRoute": { - "methods": [ - "create_http_route" - ] - }, - "CreateMesh": { - "methods": [ - "create_mesh" - ] - }, - "CreateServiceBinding": { - "methods": [ - "create_service_binding" - ] - }, - "CreateTcpRoute": { - "methods": [ - "create_tcp_route" - ] - }, - "CreateTlsRoute": { - "methods": [ - "create_tls_route" - ] - }, - "DeleteEndpointPolicy": { - "methods": [ - "delete_endpoint_policy" - ] - }, - "DeleteGateway": { - "methods": [ - "delete_gateway" - ] - }, - "DeleteGrpcRoute": { - "methods": [ - "delete_grpc_route" - ] - }, - "DeleteHttpRoute": { - "methods": [ - "delete_http_route" - ] - }, - "DeleteMesh": { - "methods": [ - "delete_mesh" - ] - }, - "DeleteServiceBinding": { - "methods": [ - "delete_service_binding" - ] - }, - "DeleteTcpRoute": { - "methods": [ - "delete_tcp_route" - ] - }, - "DeleteTlsRoute": { - "methods": [ - "delete_tls_route" - ] - }, - "GetEndpointPolicy": { - "methods": [ - "get_endpoint_policy" - ] - }, - "GetGateway": { - "methods": [ - "get_gateway" - ] - }, - "GetGrpcRoute": { - "methods": [ - "get_grpc_route" - ] - }, - "GetHttpRoute": { - "methods": [ - "get_http_route" - ] - }, - "GetMesh": { - "methods": [ - "get_mesh" - ] - }, - "GetServiceBinding": { - "methods": [ - "get_service_binding" - ] - }, - "GetTcpRoute": { - "methods": [ - "get_tcp_route" - ] - }, - "GetTlsRoute": { - "methods": [ - "get_tls_route" - ] - }, - "ListEndpointPolicies": { - "methods": [ - "list_endpoint_policies" - ] - }, - "ListGateways": { - "methods": [ - "list_gateways" - ] - }, - "ListGrpcRoutes": { - "methods": [ - "list_grpc_routes" - ] - }, - "ListHttpRoutes": { - "methods": [ - "list_http_routes" - ] - }, - "ListMeshes": { - "methods": [ - "list_meshes" - ] - }, - "ListServiceBindings": { - "methods": [ - "list_service_bindings" - ] - }, - "ListTcpRoutes": { - "methods": [ - "list_tcp_routes" - ] - }, - "ListTlsRoutes": { - "methods": [ - "list_tls_routes" - ] - }, - "UpdateEndpointPolicy": { - "methods": [ - "update_endpoint_policy" - ] - }, - "UpdateGateway": { - "methods": [ - "update_gateway" - ] - }, - "UpdateGrpcRoute": { - "methods": [ - "update_grpc_route" - ] - }, - "UpdateHttpRoute": { - "methods": [ - "update_http_route" - ] - }, - "UpdateMesh": { - "methods": [ - "update_mesh" - ] - }, - "UpdateTcpRoute": { - "methods": [ - "update_tcp_route" - ] - }, - "UpdateTlsRoute": { - "methods": [ - "update_tls_route" - ] - } - } - }, - "grpc-async": { - "libraryClient": "NetworkServicesAsyncClient", - "rpcs": { - "CreateEndpointPolicy": { - "methods": [ - "create_endpoint_policy" - ] - }, - "CreateGateway": { - "methods": [ - "create_gateway" - ] - }, - "CreateGrpcRoute": { - "methods": [ - "create_grpc_route" - ] - }, - "CreateHttpRoute": { - "methods": [ - "create_http_route" - ] - }, - "CreateMesh": { - "methods": [ - "create_mesh" - ] - }, - "CreateServiceBinding": { - "methods": [ - "create_service_binding" - ] - }, - "CreateTcpRoute": { - "methods": [ - "create_tcp_route" - ] - }, - "CreateTlsRoute": { - "methods": [ - "create_tls_route" - ] - }, - "DeleteEndpointPolicy": { - "methods": [ - "delete_endpoint_policy" - ] - }, - "DeleteGateway": { - "methods": [ - "delete_gateway" - ] - }, - "DeleteGrpcRoute": { - "methods": [ - "delete_grpc_route" - ] - }, - "DeleteHttpRoute": { - "methods": [ - "delete_http_route" - ] - }, - "DeleteMesh": { - "methods": [ - "delete_mesh" - ] - }, - "DeleteServiceBinding": { - "methods": [ - "delete_service_binding" - ] - }, - "DeleteTcpRoute": { - "methods": [ - "delete_tcp_route" - ] - }, - "DeleteTlsRoute": { - "methods": [ - "delete_tls_route" - ] - }, - "GetEndpointPolicy": { - "methods": [ - "get_endpoint_policy" - ] - }, - "GetGateway": { - "methods": [ - "get_gateway" - ] - }, - "GetGrpcRoute": { - "methods": [ - "get_grpc_route" - ] - }, - "GetHttpRoute": { - "methods": [ - "get_http_route" - ] - }, - "GetMesh": { - "methods": [ - "get_mesh" - ] - }, - "GetServiceBinding": { - "methods": [ - "get_service_binding" - ] - }, - "GetTcpRoute": { - "methods": [ - "get_tcp_route" - ] - }, - "GetTlsRoute": { - "methods": [ - "get_tls_route" - ] - }, - "ListEndpointPolicies": { - "methods": [ - "list_endpoint_policies" - ] - }, - "ListGateways": { - "methods": [ - "list_gateways" - ] - }, - "ListGrpcRoutes": { - "methods": [ - "list_grpc_routes" - ] - }, - "ListHttpRoutes": { - "methods": [ - "list_http_routes" - ] - }, - "ListMeshes": { - "methods": [ - "list_meshes" - ] - }, - "ListServiceBindings": { - "methods": [ - "list_service_bindings" - ] - }, - "ListTcpRoutes": { - "methods": [ - "list_tcp_routes" - ] - }, - "ListTlsRoutes": { - "methods": [ - "list_tls_routes" - ] - }, - "UpdateEndpointPolicy": { - "methods": [ - "update_endpoint_policy" - ] - }, - "UpdateGateway": { - "methods": [ - "update_gateway" - ] - }, - "UpdateGrpcRoute": { - "methods": [ - "update_grpc_route" - ] - }, - "UpdateHttpRoute": { - "methods": [ - "update_http_route" - ] - }, - "UpdateMesh": { - "methods": [ - "update_mesh" - ] - }, - "UpdateTcpRoute": { - "methods": [ - "update_tcp_route" - ] - }, - "UpdateTlsRoute": { - "methods": [ - "update_tls_route" - ] - } - } - }, - "rest": { - "libraryClient": "NetworkServicesClient", - "rpcs": { - "CreateEndpointPolicy": { - "methods": [ - "create_endpoint_policy" - ] - }, - "CreateGateway": { - "methods": [ - "create_gateway" - ] - }, - "CreateGrpcRoute": { - "methods": [ - "create_grpc_route" - ] - }, - "CreateHttpRoute": { - "methods": [ - "create_http_route" - ] - }, - "CreateMesh": { - "methods": [ - "create_mesh" - ] - }, - "CreateServiceBinding": { - "methods": [ - "create_service_binding" - ] - }, - "CreateTcpRoute": { - "methods": [ - "create_tcp_route" - ] - }, - "CreateTlsRoute": { - "methods": [ - "create_tls_route" - ] - }, - "DeleteEndpointPolicy": { - "methods": [ - "delete_endpoint_policy" - ] - }, - "DeleteGateway": { - "methods": [ - "delete_gateway" - ] - }, - "DeleteGrpcRoute": { - "methods": [ - "delete_grpc_route" - ] - }, - "DeleteHttpRoute": { - "methods": [ - "delete_http_route" - ] - }, - "DeleteMesh": { - "methods": [ - "delete_mesh" - ] - }, - "DeleteServiceBinding": { - "methods": [ - "delete_service_binding" - ] - }, - "DeleteTcpRoute": { - "methods": [ - "delete_tcp_route" - ] - }, - "DeleteTlsRoute": { - "methods": [ - "delete_tls_route" - ] - }, - "GetEndpointPolicy": { - "methods": [ - "get_endpoint_policy" - ] - }, - "GetGateway": { - "methods": [ - "get_gateway" - ] - }, - "GetGrpcRoute": { - "methods": [ - "get_grpc_route" - ] - }, - "GetHttpRoute": { - "methods": [ - "get_http_route" - ] - }, - "GetMesh": { - "methods": [ - "get_mesh" - ] - }, - "GetServiceBinding": { - "methods": [ - "get_service_binding" - ] - }, - "GetTcpRoute": { - "methods": [ - "get_tcp_route" - ] - }, - "GetTlsRoute": { - "methods": [ - "get_tls_route" - ] - }, - "ListEndpointPolicies": { - "methods": [ - "list_endpoint_policies" - ] - }, - "ListGateways": { - "methods": [ - "list_gateways" - ] - }, - "ListGrpcRoutes": { - "methods": [ - "list_grpc_routes" - ] - }, - "ListHttpRoutes": { - "methods": [ - "list_http_routes" - ] - }, - "ListMeshes": { - "methods": [ - "list_meshes" - ] - }, - "ListServiceBindings": { - "methods": [ - "list_service_bindings" - ] - }, - "ListTcpRoutes": { - "methods": [ - "list_tcp_routes" - ] - }, - "ListTlsRoutes": { - "methods": [ - "list_tls_routes" - ] - }, - "UpdateEndpointPolicy": { - "methods": [ - "update_endpoint_policy" - ] - }, - "UpdateGateway": { - "methods": [ - "update_gateway" - ] - }, - "UpdateGrpcRoute": { - "methods": [ - "update_grpc_route" - ] - }, - "UpdateHttpRoute": { - "methods": [ - "update_http_route" - ] - }, - "UpdateMesh": { - "methods": [ - "update_mesh" - ] - }, - "UpdateTcpRoute": { - "methods": [ - "update_tcp_route" - ] - }, - "UpdateTlsRoute": { - "methods": [ - "update_tls_route" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/google/cloud/network_services_v1/py.typed b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed deleted file mode 100644 index dfe9bf70b7d5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-services package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py deleted file mode 100644 index ffaa7e02b9ae..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 DepServiceClient -from .async_client import DepServiceAsyncClient - -__all__ = ( - 'DepServiceClient', - 'DepServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py deleted file mode 100644 index cf51a467d5fe..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/async_client.py +++ /dev/null @@ -1,2148 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_services_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 - - -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_services_v1.services.dep_service import pagers -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import dep -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DepServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport -from .client import DepServiceClient - - -class DepServiceAsyncClient: - """Service describing handlers for resources.""" - - _client: DepServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DepServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DepServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DepServiceClient._DEFAULT_UNIVERSE - - lb_route_extension_path = staticmethod(DepServiceClient.lb_route_extension_path) - parse_lb_route_extension_path = staticmethod(DepServiceClient.parse_lb_route_extension_path) - lb_traffic_extension_path = staticmethod(DepServiceClient.lb_traffic_extension_path) - parse_lb_traffic_extension_path = staticmethod(DepServiceClient.parse_lb_traffic_extension_path) - common_billing_account_path = staticmethod(DepServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DepServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DepServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DepServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DepServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DepServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DepServiceClient.common_project_path) - parse_common_project_path = staticmethod(DepServiceClient.parse_common_project_path) - common_location_path = staticmethod(DepServiceClient.common_location_path) - parse_common_location_path = staticmethod(DepServiceClient.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: - DepServiceAsyncClient: The constructed client. - """ - return DepServiceClient.from_service_account_info.__func__(DepServiceAsyncClient, 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: - DepServiceAsyncClient: The constructed client. - """ - return DepServiceClient.from_service_account_file.__func__(DepServiceAsyncClient, 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 DepServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DepServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DepServiceTransport: 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 = functools.partial(type(DepServiceClient).get_transport_class, type(DepServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DepServiceTransport, Callable[..., DepServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the dep 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,DepServiceTransport,Callable[..., DepServiceTransport]]]): - 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 DepServiceTransport 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 = DepServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_lb_traffic_extensions(self, - request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLbTrafficExtensionsAsyncPager: - r"""Lists ``LbTrafficExtension`` resources 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_services_v1 - - async def sample_list_lb_traffic_extensions(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbTrafficExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_traffic_extensions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest, dict]]): - The request object. Message for requesting list of ``LbTrafficExtension`` - resources. - parent (:class:`str`): - Required. The project and location from which the - ``LbTrafficExtension`` resources are listed, specified - in the following 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager: - Message for response to listing LbTrafficExtension - resources. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.ListLbTrafficExtensionsRequest): - request = dep.ListLbTrafficExtensionsRequest(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_lb_traffic_extensions] - - # 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.ListLbTrafficExtensionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_lb_traffic_extension(self, - request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dep.LbTrafficExtension: - r"""Gets details of the specified ``LbTrafficExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lb_traffic_extension(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest, dict]]): - The request object. Message for getting a ``LbTrafficExtension`` resource. - name (:class:`str`): - Required. A name of the ``LbTrafficExtension`` resource - to get. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.LbTrafficExtension: - LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.GetLbTrafficExtensionRequest): - request = dep.GetLbTrafficExtensionRequest(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_lb_traffic_extension] - - # Certain 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_lb_traffic_extension(self, - request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, - *, - parent: Optional[str] = None, - lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, - lb_traffic_extension_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ``LbTrafficExtension`` resource 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_services_v1 - - async def sample_create_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbTrafficExtensionRequest( - parent="parent_value", - lb_traffic_extension_id="lb_traffic_extension_id_value", - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.create_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest, dict]]): - The request object. Message for creating a ``LbTrafficExtension`` resource. - parent (:class:`str`): - Required. The parent resource of the - ``LbTrafficExtension`` resource. 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. - lb_traffic_extension (:class:`google.cloud.network_services_v1.types.LbTrafficExtension`): - Required. ``LbTrafficExtension`` resource to be created. - This corresponds to the ``lb_traffic_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lb_traffic_extension_id (:class:`str`): - Required. User-provided ID of the ``LbTrafficExtension`` - resource to be created. - - This corresponds to the ``lb_traffic_extension_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lb_traffic_extension, lb_traffic_extension_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.CreateLbTrafficExtensionRequest): - request = dep.CreateLbTrafficExtensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lb_traffic_extension is not None: - request.lb_traffic_extension = lb_traffic_extension - if lb_traffic_extension_id is not None: - request.lb_traffic_extension_id = lb_traffic_extension_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_lb_traffic_extension] - - # 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, - dep.LbTrafficExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_lb_traffic_extension(self, - request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, - *, - lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of the specified ``LbTrafficExtension`` - resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbTrafficExtensionRequest( - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.update_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest, dict]]): - The request object. Message for updating a ``LbTrafficExtension`` resource. - lb_traffic_extension (:class:`google.cloud.network_services_v1.types.LbTrafficExtension`): - Required. ``LbTrafficExtension`` resource being updated. - This corresponds to the ``lb_traffic_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Used to specify the fields to be overwritten - in the ``LbTrafficExtension`` resource by the update. - The fields specified in the update_mask are relative to - the resource, not the full request. A field is - overwritten if it is in the mask. If the user does not - specify a mask, then all fields are 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([lb_traffic_extension, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.UpdateLbTrafficExtensionRequest): - request = dep.UpdateLbTrafficExtensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if lb_traffic_extension is not None: - request.lb_traffic_extension = lb_traffic_extension - 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_lb_traffic_extension] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("lb_traffic_extension.name", request.lb_traffic_extension.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, - dep.LbTrafficExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_lb_traffic_extension(self, - request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified ``LbTrafficExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest, dict]]): - The request object. Message for deleting a ``LbTrafficExtension`` resource. - name (:class:`str`): - Required. The name of the ``LbTrafficExtension`` - resource to delete. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.DeleteLbTrafficExtensionRequest): - request = dep.DeleteLbTrafficExtensionRequest(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_lb_traffic_extension] - - # Certain 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_lb_route_extensions(self, - request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLbRouteExtensionsAsyncPager: - r"""Lists ``LbRouteExtension`` resources 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_services_v1 - - async def sample_list_lb_route_extensions(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbRouteExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_route_extensions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest, dict]]): - The request object. Message for requesting list of ``LbRouteExtension`` - resources. - parent (:class:`str`): - Required. The project and location from which the - ``LbRouteExtension`` resources are listed, specified in - the following 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager: - Message for response to listing LbRouteExtension - resources. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.ListLbRouteExtensionsRequest): - request = dep.ListLbRouteExtensionsRequest(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_lb_route_extensions] - - # 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.ListLbRouteExtensionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_lb_route_extension(self, - request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dep.LbRouteExtension: - r"""Gets details of the specified ``LbRouteExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lb_route_extension(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetLbRouteExtensionRequest, dict]]): - The request object. Message for getting a ``LbRouteExtension`` resource. - name (:class:`str`): - Required. A name of the ``LbRouteExtension`` resource to - get. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.LbRouteExtension: - LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.GetLbRouteExtensionRequest): - request = dep.GetLbRouteExtensionRequest(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_lb_route_extension] - - # Certain 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_lb_route_extension(self, - request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, - *, - parent: Optional[str] = None, - lb_route_extension: Optional[dep.LbRouteExtension] = None, - lb_route_extension_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ``LbRouteExtension`` resource 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_services_v1 - - async def sample_create_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbRouteExtensionRequest( - parent="parent_value", - lb_route_extension_id="lb_route_extension_id_value", - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.create_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest, dict]]): - The request object. Message for creating a ``LbRouteExtension`` resource. - parent (:class:`str`): - Required. The parent resource of the - ``LbRouteExtension`` resource. 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. - lb_route_extension (:class:`google.cloud.network_services_v1.types.LbRouteExtension`): - Required. ``LbRouteExtension`` resource to be created. - This corresponds to the ``lb_route_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lb_route_extension_id (:class:`str`): - Required. User-provided ID of the ``LbRouteExtension`` - resource to be created. - - This corresponds to the ``lb_route_extension_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lb_route_extension, lb_route_extension_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.CreateLbRouteExtensionRequest): - request = dep.CreateLbRouteExtensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lb_route_extension is not None: - request.lb_route_extension = lb_route_extension - if lb_route_extension_id is not None: - request.lb_route_extension_id = lb_route_extension_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_lb_route_extension] - - # 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, - dep.LbRouteExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_lb_route_extension(self, - request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, - *, - lb_route_extension: Optional[dep.LbRouteExtension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of the specified ``LbRouteExtension`` - resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbRouteExtensionRequest( - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.update_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest, dict]]): - The request object. Message for updating a ``LbRouteExtension`` resource. - lb_route_extension (:class:`google.cloud.network_services_v1.types.LbRouteExtension`): - Required. ``LbRouteExtension`` resource being updated. - This corresponds to the ``lb_route_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Used to specify the fields to be overwritten - in the ``LbRouteExtension`` resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field is overwritten - if it is in the mask. If the user does not specify a - mask, then all fields are 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([lb_route_extension, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.UpdateLbRouteExtensionRequest): - request = dep.UpdateLbRouteExtensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if lb_route_extension is not None: - request.lb_route_extension = lb_route_extension - 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_lb_route_extension] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("lb_route_extension.name", request.lb_route_extension.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, - dep.LbRouteExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_lb_route_extension(self, - request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified ``LbRouteExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest, dict]]): - The request object. Message for deleting a ``LbRouteExtension`` resource. - name (:class:`str`): - Required. The name of the ``LbRouteExtension`` resource - to delete. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, dep.DeleteLbRouteExtensionRequest): - request = dep.DeleteLbRouteExtensionRequest(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_lb_route_extension] - - # Certain 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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) -> "DepServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DepServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py deleted file mode 100644 index ac3e0906abda..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/client.py +++ /dev/null @@ -1,2498 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.network_services_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, 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_services_v1.services.dep_service import pagers -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import dep -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DepServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DepServiceGrpcTransport -from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport -from .transports.rest import DepServiceRestTransport - - -class DepServiceClientMeta(type): - """Metaclass for the DepService 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[DepServiceTransport]] - _transport_registry["grpc"] = DepServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DepServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DepServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DepServiceTransport]: - """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 DepServiceClient(metaclass=DepServiceClientMeta): - """Service describing handlers for resources.""" - - @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 = "networkservices.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{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: - DepServiceClient: 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: - DepServiceClient: 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) -> DepServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DepServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def lb_route_extension_path(project: str,location: str,lb_route_extension: str,) -> str: - """Returns a fully-qualified lb_route_extension string.""" - return "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format(project=project, location=location, lb_route_extension=lb_route_extension, ) - - @staticmethod - def parse_lb_route_extension_path(path: str) -> Dict[str,str]: - """Parses a lb_route_extension path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lbRouteExtensions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def lb_traffic_extension_path(project: str,location: str,lb_traffic_extension: str,) -> str: - """Returns a fully-qualified lb_traffic_extension string.""" - return "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format(project=project, location=location, lb_traffic_extension=lb_traffic_extension, ) - - @staticmethod - def parse_lb_traffic_extension_path(path: str) -> Dict[str,str]: - """Parses a lb_traffic_extension path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lbTrafficExtensions/(?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 = DepServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DepServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DepServiceClient._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 = DepServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DepServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DepServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @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, DepServiceTransport, Callable[..., DepServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the dep 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,DepServiceTransport,Callable[..., DepServiceTransport]]]): - 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 DepServiceTransport 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 = DepServiceClient._read_environment_variables() - self._client_cert_source = DepServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DepServiceClient._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 - - 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, DepServiceTransport) - if transport_provided: - # transport is a DepServiceTransport 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(DepServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DepServiceClient._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[DepServiceTransport], Callable[..., DepServiceTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., DepServiceTransport], 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, - ) - - def list_lb_traffic_extensions(self, - request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLbTrafficExtensionsPager: - r"""Lists ``LbTrafficExtension`` resources 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_services_v1 - - def sample_list_lb_traffic_extensions(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbTrafficExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_traffic_extensions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest, dict]): - The request object. Message for requesting list of ``LbTrafficExtension`` - resources. - parent (str): - Required. The project and location from which the - ``LbTrafficExtension`` resources are listed, specified - in the following 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsPager: - Message for response to listing LbTrafficExtension - resources. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.ListLbTrafficExtensionsRequest): - request = dep.ListLbTrafficExtensionsRequest(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_lb_traffic_extensions] - - # 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.ListLbTrafficExtensionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_lb_traffic_extension(self, - request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dep.LbTrafficExtension: - r"""Gets details of the specified ``LbTrafficExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - response = client.get_lb_traffic_extension(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest, dict]): - The request object. Message for getting a ``LbTrafficExtension`` resource. - name (str): - Required. A name of the ``LbTrafficExtension`` resource - to get. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.LbTrafficExtension: - LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.GetLbTrafficExtensionRequest): - request = dep.GetLbTrafficExtensionRequest(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_lb_traffic_extension] - - # Certain 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_lb_traffic_extension(self, - request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, - *, - parent: Optional[str] = None, - lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, - lb_traffic_extension_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new ``LbTrafficExtension`` resource 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_services_v1 - - def sample_create_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbTrafficExtensionRequest( - parent="parent_value", - lb_traffic_extension_id="lb_traffic_extension_id_value", - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.create_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest, dict]): - The request object. Message for creating a ``LbTrafficExtension`` resource. - parent (str): - Required. The parent resource of the - ``LbTrafficExtension`` resource. 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. - lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): - Required. ``LbTrafficExtension`` resource to be created. - This corresponds to the ``lb_traffic_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lb_traffic_extension_id (str): - Required. User-provided ID of the ``LbTrafficExtension`` - resource to be created. - - This corresponds to the ``lb_traffic_extension_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lb_traffic_extension, lb_traffic_extension_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.CreateLbTrafficExtensionRequest): - request = dep.CreateLbTrafficExtensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lb_traffic_extension is not None: - request.lb_traffic_extension = lb_traffic_extension - if lb_traffic_extension_id is not None: - request.lb_traffic_extension_id = lb_traffic_extension_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_lb_traffic_extension] - - # 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, - dep.LbTrafficExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_lb_traffic_extension(self, - request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, - *, - lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of the specified ``LbTrafficExtension`` - resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbTrafficExtensionRequest( - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.update_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest, dict]): - The request object. Message for updating a ``LbTrafficExtension`` resource. - lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): - Required. ``LbTrafficExtension`` resource being updated. - This corresponds to the ``lb_traffic_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Used to specify the fields to be overwritten - in the ``LbTrafficExtension`` resource by the update. - The fields specified in the update_mask are relative to - the resource, not the full request. A field is - overwritten if it is in the mask. If the user does not - specify a mask, then all fields are 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the - headers and payloads of both requests and responses - without impacting the choice of backend services or - any other security policies associated with the - backend service. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([lb_traffic_extension, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.UpdateLbTrafficExtensionRequest): - request = dep.UpdateLbTrafficExtensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if lb_traffic_extension is not None: - request.lb_traffic_extension = lb_traffic_extension - 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_lb_traffic_extension] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("lb_traffic_extension.name", request.lb_traffic_extension.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, - dep.LbTrafficExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_lb_traffic_extension(self, - request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified ``LbTrafficExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest, dict]): - The request object. Message for deleting a ``LbTrafficExtension`` resource. - name (str): - Required. The name of the ``LbTrafficExtension`` - resource to delete. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.DeleteLbTrafficExtensionRequest): - request = dep.DeleteLbTrafficExtensionRequest(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_lb_traffic_extension] - - # Certain 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_lb_route_extensions(self, - request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLbRouteExtensionsPager: - r"""Lists ``LbRouteExtension`` resources 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_services_v1 - - def sample_list_lb_route_extensions(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbRouteExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_route_extensions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest, dict]): - The request object. Message for requesting list of ``LbRouteExtension`` - resources. - parent (str): - Required. The project and location from which the - ``LbRouteExtension`` resources are listed, specified in - the following 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsPager: - Message for response to listing LbRouteExtension - resources. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.ListLbRouteExtensionsRequest): - request = dep.ListLbRouteExtensionsRequest(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_lb_route_extensions] - - # 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.ListLbRouteExtensionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_lb_route_extension(self, - request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dep.LbRouteExtension: - r"""Gets details of the specified ``LbRouteExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - response = client.get_lb_route_extension(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetLbRouteExtensionRequest, dict]): - The request object. Message for getting a ``LbRouteExtension`` resource. - name (str): - Required. A name of the ``LbRouteExtension`` resource to - get. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.LbRouteExtension: - LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.GetLbRouteExtensionRequest): - request = dep.GetLbRouteExtensionRequest(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_lb_route_extension] - - # Certain 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_lb_route_extension(self, - request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, - *, - parent: Optional[str] = None, - lb_route_extension: Optional[dep.LbRouteExtension] = None, - lb_route_extension_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new ``LbRouteExtension`` resource 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_services_v1 - - def sample_create_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbRouteExtensionRequest( - parent="parent_value", - lb_route_extension_id="lb_route_extension_id_value", - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.create_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest, dict]): - The request object. Message for creating a ``LbRouteExtension`` resource. - parent (str): - Required. The parent resource of the - ``LbRouteExtension`` resource. 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. - lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): - Required. ``LbRouteExtension`` resource to be created. - This corresponds to the ``lb_route_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lb_route_extension_id (str): - Required. User-provided ID of the ``LbRouteExtension`` - resource to be created. - - This corresponds to the ``lb_route_extension_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, lb_route_extension, lb_route_extension_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.CreateLbRouteExtensionRequest): - request = dep.CreateLbRouteExtensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lb_route_extension is not None: - request.lb_route_extension = lb_route_extension - if lb_route_extension_id is not None: - request.lb_route_extension_id = lb_route_extension_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_lb_route_extension] - - # 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, - dep.LbRouteExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_lb_route_extension(self, - request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, - *, - lb_route_extension: Optional[dep.LbRouteExtension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of the specified ``LbRouteExtension`` - resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbRouteExtensionRequest( - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.update_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest, dict]): - The request object. Message for updating a ``LbRouteExtension`` resource. - lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): - Required. ``LbRouteExtension`` resource being updated. - This corresponds to the ``lb_route_extension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Used to specify the fields to be overwritten - in the ``LbRouteExtension`` resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field is overwritten - if it is in the mask. If the user does not specify a - mask, then all fields are 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is - routed to for a given request. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([lb_route_extension, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.UpdateLbRouteExtensionRequest): - request = dep.UpdateLbRouteExtensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if lb_route_extension is not None: - request.lb_route_extension = lb_route_extension - 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_lb_route_extension] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("lb_route_extension.name", request.lb_route_extension.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, - dep.LbRouteExtension, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_lb_route_extension(self, - request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified ``LbRouteExtension`` resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest, dict]): - The request object. Message for deleting a ``LbRouteExtension`` resource. - name (str): - Required. The name of the ``LbRouteExtension`` resource - to delete. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, dep.DeleteLbRouteExtensionRequest): - request = dep.DeleteLbRouteExtensionRequest(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_lb_route_extension] - - # Certain 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) -> "DepServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DepServiceClient", -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py deleted file mode 100644 index 97c7ce22fc34..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.network_services_v1.types import dep - - -class ListLbTrafficExtensionsPager: - """A pager for iterating through ``list_lb_traffic_extensions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``lb_traffic_extensions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLbTrafficExtensions`` requests and continue to iterate - through the ``lb_traffic_extensions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` - 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[..., dep.ListLbTrafficExtensionsResponse], - request: dep.ListLbTrafficExtensionsRequest, - response: dep.ListLbTrafficExtensionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dep.ListLbTrafficExtensionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[dep.ListLbTrafficExtensionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[dep.LbTrafficExtension]: - for page in self.pages: - yield from page.lb_traffic_extensions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLbTrafficExtensionsAsyncPager: - """A pager for iterating through ``list_lb_traffic_extensions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``lb_traffic_extensions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLbTrafficExtensions`` requests and continue to iterate - through the ``lb_traffic_extensions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse` - 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[dep.ListLbTrafficExtensionsResponse]], - request: dep.ListLbTrafficExtensionsRequest, - response: dep.ListLbTrafficExtensionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListLbTrafficExtensionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dep.ListLbTrafficExtensionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[dep.ListLbTrafficExtensionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[dep.LbTrafficExtension]: - async def async_generator(): - async for page in self.pages: - for response in page.lb_traffic_extensions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLbRouteExtensionsPager: - """A pager for iterating through ``list_lb_route_extensions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``lb_route_extensions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLbRouteExtensions`` requests and continue to iterate - through the ``lb_route_extensions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` - 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[..., dep.ListLbRouteExtensionsResponse], - request: dep.ListLbRouteExtensionsRequest, - response: dep.ListLbRouteExtensionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dep.ListLbRouteExtensionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[dep.ListLbRouteExtensionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[dep.LbRouteExtension]: - for page in self.pages: - yield from page.lb_route_extensions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLbRouteExtensionsAsyncPager: - """A pager for iterating through ``list_lb_route_extensions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``lb_route_extensions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLbRouteExtensions`` requests and continue to iterate - through the ``lb_route_extensions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse` - 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[dep.ListLbRouteExtensionsResponse]], - request: dep.ListLbRouteExtensionsRequest, - response: dep.ListLbRouteExtensionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListLbRouteExtensionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dep.ListLbRouteExtensionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[dep.ListLbRouteExtensionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[dep.LbRouteExtension]: - async def async_generator(): - async for page in self.pages: - for response in page.lb_route_extensions: - 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-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py deleted file mode 100644 index e4e3e262c9ee..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 DepServiceTransport -from .grpc import DepServiceGrpcTransport -from .grpc_asyncio import DepServiceGrpcAsyncIOTransport -from .rest import DepServiceRestTransport -from .rest import DepServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DepServiceTransport]] -_transport_registry['grpc'] = DepServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DepServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DepServiceRestTransport - -__all__ = ( - 'DepServiceTransport', - 'DepServiceGrpcTransport', - 'DepServiceGrpcAsyncIOTransport', - 'DepServiceRestTransport', - 'DepServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py deleted file mode 100644 index ed22020e6315..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/base.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_services_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import dep -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__) - - -class DepServiceTransport(abc.ABC): - """Abstract transport class for DepService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networkservices.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: 'networkservices.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 no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_lb_traffic_extensions: gapic_v1.method.wrap_method( - self.list_lb_traffic_extensions, - default_timeout=None, - client_info=client_info, - ), - self.get_lb_traffic_extension: gapic_v1.method.wrap_method( - self.get_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.create_lb_traffic_extension: gapic_v1.method.wrap_method( - self.create_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.update_lb_traffic_extension: gapic_v1.method.wrap_method( - self.update_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.delete_lb_traffic_extension: gapic_v1.method.wrap_method( - self.delete_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.list_lb_route_extensions: gapic_v1.method.wrap_method( - self.list_lb_route_extensions, - default_timeout=None, - client_info=client_info, - ), - self.get_lb_route_extension: gapic_v1.method.wrap_method( - self.get_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.create_lb_route_extension: gapic_v1.method.wrap_method( - self.create_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.update_lb_route_extension: gapic_v1.method.wrap_method( - self.update_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.delete_lb_route_extension: gapic_v1.method.wrap_method( - self.delete_lb_route_extension, - 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_lb_traffic_extensions(self) -> Callable[ - [dep.ListLbTrafficExtensionsRequest], - Union[ - dep.ListLbTrafficExtensionsResponse, - Awaitable[dep.ListLbTrafficExtensionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_lb_traffic_extension(self) -> Callable[ - [dep.GetLbTrafficExtensionRequest], - Union[ - dep.LbTrafficExtension, - Awaitable[dep.LbTrafficExtension] - ]]: - raise NotImplementedError() - - @property - def create_lb_traffic_extension(self) -> Callable[ - [dep.CreateLbTrafficExtensionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_lb_traffic_extension(self) -> Callable[ - [dep.UpdateLbTrafficExtensionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_lb_traffic_extension(self) -> Callable[ - [dep.DeleteLbTrafficExtensionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_lb_route_extensions(self) -> Callable[ - [dep.ListLbRouteExtensionsRequest], - Union[ - dep.ListLbRouteExtensionsResponse, - Awaitable[dep.ListLbRouteExtensionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_lb_route_extension(self) -> Callable[ - [dep.GetLbRouteExtensionRequest], - Union[ - dep.LbRouteExtension, - Awaitable[dep.LbRouteExtension] - ]]: - raise NotImplementedError() - - @property - def create_lb_route_extension(self) -> Callable[ - [dep.CreateLbRouteExtensionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_lb_route_extension(self) -> Callable[ - [dep.UpdateLbRouteExtensionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_lb_route_extension(self) -> Callable[ - [dep.DeleteLbRouteExtensionRequest], - 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__ = ( - 'DepServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py deleted file mode 100644 index 589c48b2a03f..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc.py +++ /dev/null @@ -1,718 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import dep -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 DepServiceTransport, DEFAULT_CLIENT_INFO - - -class DepServiceGrpcTransport(DepServiceTransport): - """gRPC backend transport for DepService. - - Service describing handlers for resources. - - 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 = 'networkservices.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: 'networkservices.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 = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'networkservices.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_lb_traffic_extensions(self) -> Callable[ - [dep.ListLbTrafficExtensionsRequest], - dep.ListLbTrafficExtensionsResponse]: - r"""Return a callable for the list lb traffic extensions method over gRPC. - - Lists ``LbTrafficExtension`` resources in a given project and - location. - - Returns: - Callable[[~.ListLbTrafficExtensionsRequest], - ~.ListLbTrafficExtensionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_traffic_extensions' not in self._stubs: - self._stubs['list_lb_traffic_extensions'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/ListLbTrafficExtensions', - request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, - response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, - ) - return self._stubs['list_lb_traffic_extensions'] - - @property - def get_lb_traffic_extension(self) -> Callable[ - [dep.GetLbTrafficExtensionRequest], - dep.LbTrafficExtension]: - r"""Return a callable for the get lb traffic extension method over gRPC. - - Gets details of the specified ``LbTrafficExtension`` resource. - - Returns: - Callable[[~.GetLbTrafficExtensionRequest], - ~.LbTrafficExtension]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_traffic_extension' not in self._stubs: - self._stubs['get_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/GetLbTrafficExtension', - request_serializer=dep.GetLbTrafficExtensionRequest.serialize, - response_deserializer=dep.LbTrafficExtension.deserialize, - ) - return self._stubs['get_lb_traffic_extension'] - - @property - def create_lb_traffic_extension(self) -> Callable[ - [dep.CreateLbTrafficExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create lb traffic extension method over gRPC. - - Creates a new ``LbTrafficExtension`` resource in a given project - and location. - - Returns: - Callable[[~.CreateLbTrafficExtensionRequest], - ~.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_lb_traffic_extension' not in self._stubs: - self._stubs['create_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/CreateLbTrafficExtension', - request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_lb_traffic_extension'] - - @property - def update_lb_traffic_extension(self) -> Callable[ - [dep.UpdateLbTrafficExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update lb traffic extension method over gRPC. - - Updates the parameters of the specified ``LbTrafficExtension`` - resource. - - Returns: - Callable[[~.UpdateLbTrafficExtensionRequest], - ~.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_lb_traffic_extension' not in self._stubs: - self._stubs['update_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/UpdateLbTrafficExtension', - request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_lb_traffic_extension'] - - @property - def delete_lb_traffic_extension(self) -> Callable[ - [dep.DeleteLbTrafficExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete lb traffic extension method over gRPC. - - Deletes the specified ``LbTrafficExtension`` resource. - - Returns: - Callable[[~.DeleteLbTrafficExtensionRequest], - ~.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_lb_traffic_extension' not in self._stubs: - self._stubs['delete_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/DeleteLbTrafficExtension', - request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_lb_traffic_extension'] - - @property - def list_lb_route_extensions(self) -> Callable[ - [dep.ListLbRouteExtensionsRequest], - dep.ListLbRouteExtensionsResponse]: - r"""Return a callable for the list lb route extensions method over gRPC. - - Lists ``LbRouteExtension`` resources in a given project and - location. - - Returns: - Callable[[~.ListLbRouteExtensionsRequest], - ~.ListLbRouteExtensionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_route_extensions' not in self._stubs: - self._stubs['list_lb_route_extensions'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/ListLbRouteExtensions', - request_serializer=dep.ListLbRouteExtensionsRequest.serialize, - response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, - ) - return self._stubs['list_lb_route_extensions'] - - @property - def get_lb_route_extension(self) -> Callable[ - [dep.GetLbRouteExtensionRequest], - dep.LbRouteExtension]: - r"""Return a callable for the get lb route extension method over gRPC. - - Gets details of the specified ``LbRouteExtension`` resource. - - Returns: - Callable[[~.GetLbRouteExtensionRequest], - ~.LbRouteExtension]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_route_extension' not in self._stubs: - self._stubs['get_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/GetLbRouteExtension', - request_serializer=dep.GetLbRouteExtensionRequest.serialize, - response_deserializer=dep.LbRouteExtension.deserialize, - ) - return self._stubs['get_lb_route_extension'] - - @property - def create_lb_route_extension(self) -> Callable[ - [dep.CreateLbRouteExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create lb route extension method over gRPC. - - Creates a new ``LbRouteExtension`` resource in a given project - and location. - - Returns: - Callable[[~.CreateLbRouteExtensionRequest], - ~.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_lb_route_extension' not in self._stubs: - self._stubs['create_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/CreateLbRouteExtension', - request_serializer=dep.CreateLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_lb_route_extension'] - - @property - def update_lb_route_extension(self) -> Callable[ - [dep.UpdateLbRouteExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update lb route extension method over gRPC. - - Updates the parameters of the specified ``LbRouteExtension`` - resource. - - Returns: - Callable[[~.UpdateLbRouteExtensionRequest], - ~.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_lb_route_extension' not in self._stubs: - self._stubs['update_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/UpdateLbRouteExtension', - request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_lb_route_extension'] - - @property - def delete_lb_route_extension(self) -> Callable[ - [dep.DeleteLbRouteExtensionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete lb route extension method over gRPC. - - Deletes the specified ``LbRouteExtension`` resource. - - Returns: - Callable[[~.DeleteLbRouteExtensionRequest], - ~.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_lb_route_extension' not in self._stubs: - self._stubs['delete_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/DeleteLbRouteExtension', - request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_lb_route_extension'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DepServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py deleted file mode 100644 index cdd21e8e0f62..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,773 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import dep -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 DepServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DepServiceGrpcTransport - - -class DepServiceGrpcAsyncIOTransport(DepServiceTransport): - """gRPC AsyncIO backend transport for DepService. - - Service describing handlers for resources. - - 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 = 'networkservices.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 = 'networkservices.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: 'networkservices.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 = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_lb_traffic_extensions(self) -> Callable[ - [dep.ListLbTrafficExtensionsRequest], - Awaitable[dep.ListLbTrafficExtensionsResponse]]: - r"""Return a callable for the list lb traffic extensions method over gRPC. - - Lists ``LbTrafficExtension`` resources in a given project and - location. - - Returns: - Callable[[~.ListLbTrafficExtensionsRequest], - Awaitable[~.ListLbTrafficExtensionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_traffic_extensions' not in self._stubs: - self._stubs['list_lb_traffic_extensions'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/ListLbTrafficExtensions', - request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, - response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, - ) - return self._stubs['list_lb_traffic_extensions'] - - @property - def get_lb_traffic_extension(self) -> Callable[ - [dep.GetLbTrafficExtensionRequest], - Awaitable[dep.LbTrafficExtension]]: - r"""Return a callable for the get lb traffic extension method over gRPC. - - Gets details of the specified ``LbTrafficExtension`` resource. - - Returns: - Callable[[~.GetLbTrafficExtensionRequest], - Awaitable[~.LbTrafficExtension]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_traffic_extension' not in self._stubs: - self._stubs['get_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/GetLbTrafficExtension', - request_serializer=dep.GetLbTrafficExtensionRequest.serialize, - response_deserializer=dep.LbTrafficExtension.deserialize, - ) - return self._stubs['get_lb_traffic_extension'] - - @property - def create_lb_traffic_extension(self) -> Callable[ - [dep.CreateLbTrafficExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create lb traffic extension method over gRPC. - - Creates a new ``LbTrafficExtension`` resource in a given project - and location. - - Returns: - Callable[[~.CreateLbTrafficExtensionRequest], - 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_lb_traffic_extension' not in self._stubs: - self._stubs['create_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/CreateLbTrafficExtension', - request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_lb_traffic_extension'] - - @property - def update_lb_traffic_extension(self) -> Callable[ - [dep.UpdateLbTrafficExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update lb traffic extension method over gRPC. - - Updates the parameters of the specified ``LbTrafficExtension`` - resource. - - Returns: - Callable[[~.UpdateLbTrafficExtensionRequest], - 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_lb_traffic_extension' not in self._stubs: - self._stubs['update_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/UpdateLbTrafficExtension', - request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_lb_traffic_extension'] - - @property - def delete_lb_traffic_extension(self) -> Callable[ - [dep.DeleteLbTrafficExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete lb traffic extension method over gRPC. - - Deletes the specified ``LbTrafficExtension`` resource. - - Returns: - Callable[[~.DeleteLbTrafficExtensionRequest], - 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_lb_traffic_extension' not in self._stubs: - self._stubs['delete_lb_traffic_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/DeleteLbTrafficExtension', - request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_lb_traffic_extension'] - - @property - def list_lb_route_extensions(self) -> Callable[ - [dep.ListLbRouteExtensionsRequest], - Awaitable[dep.ListLbRouteExtensionsResponse]]: - r"""Return a callable for the list lb route extensions method over gRPC. - - Lists ``LbRouteExtension`` resources in a given project and - location. - - Returns: - Callable[[~.ListLbRouteExtensionsRequest], - Awaitable[~.ListLbRouteExtensionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_route_extensions' not in self._stubs: - self._stubs['list_lb_route_extensions'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/ListLbRouteExtensions', - request_serializer=dep.ListLbRouteExtensionsRequest.serialize, - response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, - ) - return self._stubs['list_lb_route_extensions'] - - @property - def get_lb_route_extension(self) -> Callable[ - [dep.GetLbRouteExtensionRequest], - Awaitable[dep.LbRouteExtension]]: - r"""Return a callable for the get lb route extension method over gRPC. - - Gets details of the specified ``LbRouteExtension`` resource. - - Returns: - Callable[[~.GetLbRouteExtensionRequest], - Awaitable[~.LbRouteExtension]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_lb_route_extension' not in self._stubs: - self._stubs['get_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/GetLbRouteExtension', - request_serializer=dep.GetLbRouteExtensionRequest.serialize, - response_deserializer=dep.LbRouteExtension.deserialize, - ) - return self._stubs['get_lb_route_extension'] - - @property - def create_lb_route_extension(self) -> Callable[ - [dep.CreateLbRouteExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create lb route extension method over gRPC. - - Creates a new ``LbRouteExtension`` resource in a given project - and location. - - Returns: - Callable[[~.CreateLbRouteExtensionRequest], - 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_lb_route_extension' not in self._stubs: - self._stubs['create_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/CreateLbRouteExtension', - request_serializer=dep.CreateLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_lb_route_extension'] - - @property - def update_lb_route_extension(self) -> Callable[ - [dep.UpdateLbRouteExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update lb route extension method over gRPC. - - Updates the parameters of the specified ``LbRouteExtension`` - resource. - - Returns: - Callable[[~.UpdateLbRouteExtensionRequest], - 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_lb_route_extension' not in self._stubs: - self._stubs['update_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/UpdateLbRouteExtension', - request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_lb_route_extension'] - - @property - def delete_lb_route_extension(self) -> Callable[ - [dep.DeleteLbRouteExtensionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete lb route extension method over gRPC. - - Deletes the specified ``LbRouteExtension`` resource. - - Returns: - Callable[[~.DeleteLbRouteExtensionRequest], - 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_lb_route_extension' not in self._stubs: - self._stubs['delete_lb_route_extension'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.DepService/DeleteLbRouteExtension', - request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_lb_route_extension'] - - 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_lb_traffic_extensions: gapic_v1.method_async.wrap_method( - self.list_lb_traffic_extensions, - default_timeout=None, - client_info=client_info, - ), - self.get_lb_traffic_extension: gapic_v1.method_async.wrap_method( - self.get_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.create_lb_traffic_extension: gapic_v1.method_async.wrap_method( - self.create_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.update_lb_traffic_extension: gapic_v1.method_async.wrap_method( - self.update_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.delete_lb_traffic_extension: gapic_v1.method_async.wrap_method( - self.delete_lb_traffic_extension, - default_timeout=None, - client_info=client_info, - ), - self.list_lb_route_extensions: gapic_v1.method_async.wrap_method( - self.list_lb_route_extensions, - default_timeout=None, - client_info=client_info, - ), - self.get_lb_route_extension: gapic_v1.method_async.wrap_method( - self.get_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.create_lb_route_extension: gapic_v1.method_async.wrap_method( - self.create_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.update_lb_route_extension: gapic_v1.method_async.wrap_method( - self.update_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - self.delete_lb_route_extension: gapic_v1.method_async.wrap_method( - self.delete_lb_route_extension, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'DepServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py deleted file mode 100644 index e1cc3a736fec..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/dep_service/transports/rest.py +++ /dev/null @@ -1,2226 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.network_services_v1.types import dep -from google.longrunning import operations_pb2 # type: ignore - -from .base import DepServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DepServiceRestInterceptor: - """Interceptor for DepService. - - 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 DepServiceRestTransport. - - .. code-block:: python - class MyCustomDepServiceInterceptor(DepServiceRestInterceptor): - def pre_create_lb_route_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_lb_route_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_lb_traffic_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_lb_traffic_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_lb_route_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_lb_route_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_lb_traffic_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_lb_traffic_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_lb_route_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_lb_route_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_lb_traffic_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_lb_traffic_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_lb_route_extensions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_lb_route_extensions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_lb_traffic_extensions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_lb_traffic_extensions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_lb_route_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_lb_route_extension(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_lb_traffic_extension(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_lb_traffic_extension(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DepServiceRestTransport(interceptor=MyCustomDepServiceInterceptor()) - client = DepServiceClient(transport=transport) - - - """ - def pre_create_lb_route_extension(self, request: dep.CreateLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.CreateLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_lb_route_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_create_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_lb_route_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_create_lb_traffic_extension(self, request: dep.CreateLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.CreateLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_lb_traffic_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_create_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_lb_traffic_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_delete_lb_route_extension(self, request: dep.DeleteLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.DeleteLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_lb_route_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_delete_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_lb_route_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_delete_lb_traffic_extension(self, request: dep.DeleteLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.DeleteLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_lb_traffic_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_delete_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_lb_traffic_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_get_lb_route_extension(self, request: dep.GetLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.GetLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_lb_route_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_get_lb_route_extension(self, response: dep.LbRouteExtension) -> dep.LbRouteExtension: - """Post-rpc interceptor for get_lb_route_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_get_lb_traffic_extension(self, request: dep.GetLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.GetLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_lb_traffic_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_get_lb_traffic_extension(self, response: dep.LbTrafficExtension) -> dep.LbTrafficExtension: - """Post-rpc interceptor for get_lb_traffic_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_list_lb_route_extensions(self, request: dep.ListLbRouteExtensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.ListLbRouteExtensionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_lb_route_extensions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_list_lb_route_extensions(self, response: dep.ListLbRouteExtensionsResponse) -> dep.ListLbRouteExtensionsResponse: - """Post-rpc interceptor for list_lb_route_extensions - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_list_lb_traffic_extensions(self, request: dep.ListLbTrafficExtensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.ListLbTrafficExtensionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_lb_traffic_extensions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_list_lb_traffic_extensions(self, response: dep.ListLbTrafficExtensionsResponse) -> dep.ListLbTrafficExtensionsResponse: - """Post-rpc interceptor for list_lb_traffic_extensions - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_update_lb_route_extension(self, request: dep.UpdateLbRouteExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.UpdateLbRouteExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_lb_route_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_update_lb_route_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_lb_route_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - def pre_update_lb_traffic_extension(self, request: dep.UpdateLbTrafficExtensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[dep.UpdateLbTrafficExtensionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_lb_traffic_extension - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService server. - """ - return request, metadata - - def post_update_lb_traffic_extension(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_lb_traffic_extension - - Override in a subclass to manipulate the response - after it is returned by the DepService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DepService 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 DepService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DepServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DepServiceRestInterceptor - - -class DepServiceRestTransport(DepServiceTransport): - """REST backend transport for DepService. - - Service describing handlers for resources. - - 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 = 'networkservices.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[DepServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networkservices.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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DepServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateLbRouteExtension(DepServiceRestStub): - def __hash__(self): - return hash("CreateLbRouteExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "lbRouteExtensionId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.CreateLbRouteExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create lb route extension method over HTTP. - - Args: - request (~.dep.CreateLbRouteExtensionRequest): - The request object. Message for creating a ``LbRouteExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/lbRouteExtensions', - 'body': 'lb_route_extension', - }, - ] - request, metadata = self._interceptor.pre_create_lb_route_extension(request, metadata) - pb_request = dep.CreateLbRouteExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_lb_route_extension(resp) - return resp - - class _CreateLbTrafficExtension(DepServiceRestStub): - def __hash__(self): - return hash("CreateLbTrafficExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "lbTrafficExtensionId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.CreateLbTrafficExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create lb traffic - extension method over HTTP. - - Args: - request (~.dep.CreateLbTrafficExtensionRequest): - The request object. Message for creating a ``LbTrafficExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/lbTrafficExtensions', - 'body': 'lb_traffic_extension', - }, - ] - request, metadata = self._interceptor.pre_create_lb_traffic_extension(request, metadata) - pb_request = dep.CreateLbTrafficExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_lb_traffic_extension(resp) - return resp - - class _DeleteLbRouteExtension(DepServiceRestStub): - def __hash__(self): - return hash("DeleteLbRouteExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.DeleteLbRouteExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete lb route extension method over HTTP. - - Args: - request (~.dep.DeleteLbRouteExtensionRequest): - The request object. Message for deleting a ``LbRouteExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/lbRouteExtensions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_lb_route_extension(request, metadata) - pb_request = dep.DeleteLbRouteExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_lb_route_extension(resp) - return resp - - class _DeleteLbTrafficExtension(DepServiceRestStub): - def __hash__(self): - return hash("DeleteLbTrafficExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.DeleteLbTrafficExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete lb traffic - extension method over HTTP. - - Args: - request (~.dep.DeleteLbTrafficExtensionRequest): - The request object. Message for deleting a ``LbTrafficExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/lbTrafficExtensions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_lb_traffic_extension(request, metadata) - pb_request = dep.DeleteLbTrafficExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_lb_traffic_extension(resp) - return resp - - class _GetLbRouteExtension(DepServiceRestStub): - def __hash__(self): - return hash("GetLbRouteExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.GetLbRouteExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dep.LbRouteExtension: - r"""Call the get lb route extension method over HTTP. - - Args: - request (~.dep.GetLbRouteExtensionRequest): - The request object. Message for getting a ``LbRouteExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dep.LbRouteExtension: - ``LbRouteExtension`` is a resource that lets you control - where traffic is routed to for a given request. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/lbRouteExtensions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_lb_route_extension(request, metadata) - pb_request = dep.GetLbRouteExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dep.LbRouteExtension() - pb_resp = dep.LbRouteExtension.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_lb_route_extension(resp) - return resp - - class _GetLbTrafficExtension(DepServiceRestStub): - def __hash__(self): - return hash("GetLbTrafficExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.GetLbTrafficExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dep.LbTrafficExtension: - r"""Call the get lb traffic extension method over HTTP. - - Args: - request (~.dep.GetLbTrafficExtensionRequest): - The request object. Message for getting a ``LbTrafficExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dep.LbTrafficExtension: - ``LbTrafficExtension`` is a resource that lets the - extension service modify the headers and payloads of - both requests and responses without impacting the choice - of backend services or any other security policies - associated with the backend service. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/lbTrafficExtensions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_lb_traffic_extension(request, metadata) - pb_request = dep.GetLbTrafficExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dep.LbTrafficExtension() - pb_resp = dep.LbTrafficExtension.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_lb_traffic_extension(resp) - return resp - - class _ListLbRouteExtensions(DepServiceRestStub): - def __hash__(self): - return hash("ListLbRouteExtensions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.ListLbRouteExtensionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dep.ListLbRouteExtensionsResponse: - r"""Call the list lb route extensions method over HTTP. - - Args: - request (~.dep.ListLbRouteExtensionsRequest): - The request object. Message for requesting list of ``LbRouteExtension`` - resources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dep.ListLbRouteExtensionsResponse: - Message for response to listing ``LbRouteExtension`` - resources. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/lbRouteExtensions', - }, - ] - request, metadata = self._interceptor.pre_list_lb_route_extensions(request, metadata) - pb_request = dep.ListLbRouteExtensionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dep.ListLbRouteExtensionsResponse() - pb_resp = dep.ListLbRouteExtensionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_lb_route_extensions(resp) - return resp - - class _ListLbTrafficExtensions(DepServiceRestStub): - def __hash__(self): - return hash("ListLbTrafficExtensions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.ListLbTrafficExtensionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> dep.ListLbTrafficExtensionsResponse: - r"""Call the list lb traffic - extensions method over HTTP. - - Args: - request (~.dep.ListLbTrafficExtensionsRequest): - The request object. Message for requesting list of ``LbTrafficExtension`` - resources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.dep.ListLbTrafficExtensionsResponse: - Message for response to listing ``LbTrafficExtension`` - resources. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/lbTrafficExtensions', - }, - ] - request, metadata = self._interceptor.pre_list_lb_traffic_extensions(request, metadata) - pb_request = dep.ListLbTrafficExtensionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = dep.ListLbTrafficExtensionsResponse() - pb_resp = dep.ListLbTrafficExtensionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_lb_traffic_extensions(resp) - return resp - - class _UpdateLbRouteExtension(DepServiceRestStub): - def __hash__(self): - return hash("UpdateLbRouteExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.UpdateLbRouteExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update lb route extension method over HTTP. - - Args: - request (~.dep.UpdateLbRouteExtensionRequest): - The request object. Message for updating a ``LbRouteExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}', - 'body': 'lb_route_extension', - }, - ] - request, metadata = self._interceptor.pre_update_lb_route_extension(request, metadata) - pb_request = dep.UpdateLbRouteExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_lb_route_extension(resp) - return resp - - class _UpdateLbTrafficExtension(DepServiceRestStub): - def __hash__(self): - return hash("UpdateLbTrafficExtension") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: dep.UpdateLbTrafficExtensionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update lb traffic - extension method over HTTP. - - Args: - request (~.dep.UpdateLbTrafficExtensionRequest): - The request object. Message for updating a ``LbTrafficExtension`` resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}', - 'body': 'lb_traffic_extension', - }, - ] - request, metadata = self._interceptor.pre_update_lb_traffic_extension(request, metadata) - pb_request = dep.UpdateLbTrafficExtensionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_lb_traffic_extension(resp) - return resp - - @property - def create_lb_route_extension(self) -> Callable[ - [dep.CreateLbRouteExtensionRequest], - 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._CreateLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_lb_traffic_extension(self) -> Callable[ - [dep.CreateLbTrafficExtensionRequest], - 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._CreateLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_lb_route_extension(self) -> Callable[ - [dep.DeleteLbRouteExtensionRequest], - 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._DeleteLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_lb_traffic_extension(self) -> Callable[ - [dep.DeleteLbTrafficExtensionRequest], - 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._DeleteLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_lb_route_extension(self) -> Callable[ - [dep.GetLbRouteExtensionRequest], - dep.LbRouteExtension]: - # 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._GetLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_lb_traffic_extension(self) -> Callable[ - [dep.GetLbTrafficExtensionRequest], - dep.LbTrafficExtension]: - # 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._GetLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_lb_route_extensions(self) -> Callable[ - [dep.ListLbRouteExtensionsRequest], - dep.ListLbRouteExtensionsResponse]: - # 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._ListLbRouteExtensions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_lb_traffic_extensions(self) -> Callable[ - [dep.ListLbTrafficExtensionsRequest], - dep.ListLbTrafficExtensionsResponse]: - # 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._ListLbTrafficExtensions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_lb_route_extension(self) -> Callable[ - [dep.UpdateLbRouteExtensionRequest], - 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._UpdateLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_lb_traffic_extension(self) -> Callable[ - [dep.UpdateLbTrafficExtensionRequest], - 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._UpdateLbTrafficExtension(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(DepServiceRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DepServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(DepServiceRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(DepServiceRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(DepServiceRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DepServiceRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(DepServiceRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DepServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DepServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DepServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py deleted file mode 100644 index 1711b5d29828..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 NetworkServicesClient -from .async_client import NetworkServicesAsyncClient - -__all__ = ( - 'NetworkServicesClient', - 'NetworkServicesAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py deleted file mode 100644 index a4efe8d12e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/async_client.py +++ /dev/null @@ -1,5791 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_services_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 - - -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_services_v1.services.network_services import pagers -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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 NetworkServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport -from .client import NetworkServicesClient - - -class NetworkServicesAsyncClient: - """""" - - _client: NetworkServicesClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = NetworkServicesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = NetworkServicesClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = NetworkServicesClient._DEFAULT_UNIVERSE - - authorization_policy_path = staticmethod(NetworkServicesClient.authorization_policy_path) - parse_authorization_policy_path = staticmethod(NetworkServicesClient.parse_authorization_policy_path) - backend_service_path = staticmethod(NetworkServicesClient.backend_service_path) - parse_backend_service_path = staticmethod(NetworkServicesClient.parse_backend_service_path) - client_tls_policy_path = staticmethod(NetworkServicesClient.client_tls_policy_path) - parse_client_tls_policy_path = staticmethod(NetworkServicesClient.parse_client_tls_policy_path) - endpoint_policy_path = staticmethod(NetworkServicesClient.endpoint_policy_path) - parse_endpoint_policy_path = staticmethod(NetworkServicesClient.parse_endpoint_policy_path) - gateway_path = staticmethod(NetworkServicesClient.gateway_path) - parse_gateway_path = staticmethod(NetworkServicesClient.parse_gateway_path) - grpc_route_path = staticmethod(NetworkServicesClient.grpc_route_path) - parse_grpc_route_path = staticmethod(NetworkServicesClient.parse_grpc_route_path) - http_route_path = staticmethod(NetworkServicesClient.http_route_path) - parse_http_route_path = staticmethod(NetworkServicesClient.parse_http_route_path) - mesh_path = staticmethod(NetworkServicesClient.mesh_path) - parse_mesh_path = staticmethod(NetworkServicesClient.parse_mesh_path) - server_tls_policy_path = staticmethod(NetworkServicesClient.server_tls_policy_path) - parse_server_tls_policy_path = staticmethod(NetworkServicesClient.parse_server_tls_policy_path) - service_binding_path = staticmethod(NetworkServicesClient.service_binding_path) - parse_service_binding_path = staticmethod(NetworkServicesClient.parse_service_binding_path) - tcp_route_path = staticmethod(NetworkServicesClient.tcp_route_path) - parse_tcp_route_path = staticmethod(NetworkServicesClient.parse_tcp_route_path) - tls_route_path = staticmethod(NetworkServicesClient.tls_route_path) - parse_tls_route_path = staticmethod(NetworkServicesClient.parse_tls_route_path) - common_billing_account_path = staticmethod(NetworkServicesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(NetworkServicesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(NetworkServicesClient.common_folder_path) - parse_common_folder_path = staticmethod(NetworkServicesClient.parse_common_folder_path) - common_organization_path = staticmethod(NetworkServicesClient.common_organization_path) - parse_common_organization_path = staticmethod(NetworkServicesClient.parse_common_organization_path) - common_project_path = staticmethod(NetworkServicesClient.common_project_path) - parse_common_project_path = staticmethod(NetworkServicesClient.parse_common_project_path) - common_location_path = staticmethod(NetworkServicesClient.common_location_path) - parse_common_location_path = staticmethod(NetworkServicesClient.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: - NetworkServicesAsyncClient: The constructed client. - """ - return NetworkServicesClient.from_service_account_info.__func__(NetworkServicesAsyncClient, 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: - NetworkServicesAsyncClient: The constructed client. - """ - return NetworkServicesClient.from_service_account_file.__func__(NetworkServicesAsyncClient, 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 NetworkServicesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> NetworkServicesTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkServicesTransport: 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 = functools.partial(type(NetworkServicesClient).get_transport_class, type(NetworkServicesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkServicesTransport, Callable[..., NetworkServicesTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network services 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,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): - 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 NetworkServicesTransport 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 = NetworkServicesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_endpoint_policies(self, - request: Optional[Union[endpoint_policy.ListEndpointPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointPoliciesAsyncPager: - r"""Lists EndpointPolicies 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_services_v1 - - async def sample_list_endpoint_policies(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListEndpointPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_endpoint_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListEndpointPoliciesRequest, dict]]): - The request object. Request used with the - ListEndpointPolicies method. - parent (:class:`str`): - Required. The project and location from which the - EndpointPolicies should be listed, specified in the - format ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesAsyncPager: - Response returned by the - ListEndpointPolicies 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, endpoint_policy.ListEndpointPoliciesRequest): - request = endpoint_policy.ListEndpointPoliciesRequest(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_endpoint_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.ListEndpointPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_endpoint_policy(self, - request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint_policy.EndpointPolicy: - r"""Gets details of a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_endpoint_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetEndpointPolicyRequest, dict]]): - The request object. Request used with the - GetEndpointPolicy method. - name (:class:`str`): - Required. A name of the EndpointPolicy to get. Must be - in the format - ``projects/*/locations/global/endpointPolicies/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.EndpointPolicy: - EndpointPolicy is a resource that - helps apply desired configuration on the - endpoints that match specific criteria. - For example, this resource can be used - to apply "authentication config" an all - endpoints that serve on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, endpoint_policy.GetEndpointPolicyRequest): - request = endpoint_policy.GetEndpointPolicyRequest(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_endpoint_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_endpoint_policy(self, - request: Optional[Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, - endpoint_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new EndpointPolicy 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_services_v1 - - async def sample_create_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.CreateEndpointPolicyRequest( - parent="parent_value", - endpoint_policy_id="endpoint_policy_id_value", - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.create_endpoint_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_services_v1.types.CreateEndpointPolicyRequest, dict]]): - The request object. Request used with the - CreateEndpointPolicy method. - parent (:class:`str`): - Required. The parent resource of the EndpointPolicy. - Must be in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_policy (:class:`google.cloud.network_services_v1.types.EndpointPolicy`): - Required. EndpointPolicy resource to - be created. - - This corresponds to the ``endpoint_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_policy_id (:class:`str`): - Required. Short name of the - EndpointPolicy resource to be created. - E.g. "CustomECS". - - This corresponds to the ``endpoint_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration - on the endpoints that match specific criteria. For - example, this resource can be used to apply - "authentication config" an all endpoints that serve - on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, endpoint_policy, endpoint_policy_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_endpoint_policy.CreateEndpointPolicyRequest): - request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint_policy is not None: - request.endpoint_policy = endpoint_policy - if endpoint_policy_id is not None: - request.endpoint_policy_id = endpoint_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_endpoint_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_endpoint_policy.EndpointPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_endpoint_policy(self, - request: Optional[Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict]] = None, - *, - endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.UpdateEndpointPolicyRequest( - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.update_endpoint_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_services_v1.types.UpdateEndpointPolicyRequest, dict]]): - The request object. Request used with the - UpdateEndpointPolicy method. - endpoint_policy (:class:`google.cloud.network_services_v1.types.EndpointPolicy`): - Required. Updated EndpointPolicy - resource. - - This corresponds to the ``endpoint_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 EndpointPolicy 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration - on the endpoints that match specific criteria. For - example, this resource can be used to apply - "authentication config" an all endpoints that serve - on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint_policy, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_endpoint_policy.UpdateEndpointPolicyRequest): - request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint_policy is not None: - request.endpoint_policy = endpoint_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_endpoint_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint_policy.name", request.endpoint_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_endpoint_policy.EndpointPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_endpoint_policy(self, - request: Optional[Union[endpoint_policy.DeleteEndpointPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_endpoint_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_services_v1.types.DeleteEndpointPolicyRequest, dict]]): - The request object. Request used with the - DeleteEndpointPolicy method. - name (:class:`str`): - Required. A name of the EndpointPolicy to delete. Must - be in the format - ``projects/*/locations/global/endpointPolicies/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, endpoint_policy.DeleteEndpointPolicyRequest): - request = endpoint_policy.DeleteEndpointPolicyRequest(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_endpoint_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_gateways(self, - request: Optional[Union[gateway.ListGatewaysRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGatewaysAsyncPager: - r"""Lists Gateways 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_services_v1 - - async def sample_list_gateways(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListGatewaysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gateways(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListGatewaysRequest, dict]]): - The request object. Request used with the ListGateways - method. - parent (:class:`str`): - Required. The project and location from which the - Gateways should be listed, specified in the format - ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysAsyncPager: - Response returned by the ListGateways - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, gateway.ListGatewaysRequest): - request = gateway.ListGatewaysRequest(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_gateways] - - # 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.ListGatewaysAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_gateway(self, - request: Optional[Union[gateway.GetGatewayRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gateway.Gateway: - r"""Gets details of a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetGatewayRequest( - name="name_value", - ) - - # Make the request - response = await client.get_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetGatewayRequest, dict]]): - The request object. Request used by the GetGateway - method. - name (:class:`str`): - Required. A name of the Gateway to get. Must be in the - format ``projects/*/locations/*/gateways/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.Gateway: - Gateway represents the configuration - for a proxy, typically a load balancer. - It captures the ip:port over which the - services are exposed by the proxy, along - with any policy configurations. Routes - have reference to to Gateways to dictate - how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, gateway.GetGatewayRequest): - request = gateway.GetGatewayRequest(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_gateway] - - # Certain 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_gateway(self, - request: Optional[Union[gcn_gateway.CreateGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway: Optional[gcn_gateway.Gateway] = None, - gateway_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new Gateway 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_services_v1 - - async def sample_create_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.CreateGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - gateway=gateway, - ) - - # Make the request - operation = client.create_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateGatewayRequest, dict]]): - The request object. Request used by the CreateGateway - method. - parent (:class:`str`): - Required. The parent resource of the Gateway. Must be in - the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway (:class:`google.cloud.network_services_v1.types.Gateway`): - Required. Gateway resource to be - created. - - This corresponds to the ``gateway`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (:class:`str`): - Required. Short name of the Gateway - resource to be created. - - This corresponds to the ``gateway_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. - It captures the ip:port over which the services are - exposed by the proxy, along with any policy - configurations. Routes have reference to to Gateways - to dictate how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway, gateway_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_gateway.CreateGatewayRequest): - request = gcn_gateway.CreateGatewayRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway is not None: - request.gateway = gateway - if gateway_id is not None: - request.gateway_id = gateway_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_gateway] - - # 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_gateway.Gateway, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_gateway(self, - request: Optional[Union[gcn_gateway.UpdateGatewayRequest, dict]] = None, - *, - gateway: Optional[gcn_gateway.Gateway] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.UpdateGatewayRequest( - gateway=gateway, - ) - - # Make the request - operation = client.update_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateGatewayRequest, dict]]): - The request object. Request used by the UpdateGateway - method. - gateway (:class:`google.cloud.network_services_v1.types.Gateway`): - Required. Updated Gateway resource. - This corresponds to the ``gateway`` 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 Gateway 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. - It captures the ip:port over which the services are - exposed by the proxy, along with any policy - configurations. Routes have reference to to Gateways - to dictate how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([gateway, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_gateway.UpdateGatewayRequest): - request = gcn_gateway.UpdateGatewayRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if gateway is not None: - request.gateway = gateway - 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_gateway] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("gateway.name", request.gateway.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_gateway.Gateway, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_gateway(self, - request: Optional[Union[gateway.DeleteGatewayRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGatewayRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteGatewayRequest, dict]]): - The request object. Request used by the DeleteGateway - method. - name (:class:`str`): - Required. A name of the Gateway to delete. Must be in - the format ``projects/*/locations/*/gateways/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, gateway.DeleteGatewayRequest): - request = gateway.DeleteGatewayRequest(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_gateway] - - # Certain 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_grpc_routes(self, - request: Optional[Union[grpc_route.ListGrpcRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGrpcRoutesAsyncPager: - r"""Lists GrpcRoutes 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_services_v1 - - async def sample_list_grpc_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListGrpcRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_grpc_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListGrpcRoutesRequest, dict]]): - The request object. Request used with the ListGrpcRoutes - method. - parent (:class:`str`): - Required. The project and location from which the - GrpcRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesAsyncPager: - Response returned by the - ListGrpcRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, grpc_route.ListGrpcRoutesRequest): - request = grpc_route.ListGrpcRoutesRequest(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_grpc_routes] - - # 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.ListGrpcRoutesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_grpc_route(self, - request: Optional[Union[grpc_route.GetGrpcRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grpc_route.GrpcRoute: - r"""Gets details of a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetGrpcRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_grpc_route(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetGrpcRouteRequest, dict]]): - The request object. Request used by the GetGrpcRoute - method. - name (:class:`str`): - Required. A name of the GrpcRoute to get. Must be in the - format ``projects/*/locations/global/grpcRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.GrpcRoute: - GrpcRoute is the resource defining - how gRPC traffic routed by a Mesh or - Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, grpc_route.GetGrpcRouteRequest): - request = grpc_route.GetGrpcRouteRequest(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_grpc_route] - - # Certain 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_grpc_route(self, - request: Optional[Union[gcn_grpc_route.CreateGrpcRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, - grpc_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new GrpcRoute 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_services_v1 - - async def sample_create_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateGrpcRouteRequest( - parent="parent_value", - grpc_route_id="grpc_route_id_value", - grpc_route=grpc_route, - ) - - # Make the request - operation = client.create_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateGrpcRouteRequest, dict]]): - The request object. Request used by the CreateGrpcRoute - method. - parent (:class:`str`): - Required. The parent resource of the GrpcRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - grpc_route (:class:`google.cloud.network_services_v1.types.GrpcRoute`): - Required. GrpcRoute resource to be - created. - - This corresponds to the ``grpc_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - grpc_route_id (:class:`str`): - Required. Short name of the GrpcRoute - resource to be created. - - This corresponds to the ``grpc_route_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh - or Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, grpc_route, grpc_route_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_grpc_route.CreateGrpcRouteRequest): - request = gcn_grpc_route.CreateGrpcRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if grpc_route is not None: - request.grpc_route = grpc_route - if grpc_route_id is not None: - request.grpc_route_id = grpc_route_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_grpc_route] - - # 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_grpc_route.GrpcRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_grpc_route(self, - request: Optional[Union[gcn_grpc_route.UpdateGrpcRouteRequest, dict]] = None, - *, - grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateGrpcRouteRequest( - grpc_route=grpc_route, - ) - - # Make the request - operation = client.update_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateGrpcRouteRequest, dict]]): - The request object. Request used by the UpdateGrpcRoute - method. - grpc_route (:class:`google.cloud.network_services_v1.types.GrpcRoute`): - Required. Updated GrpcRoute resource. - This corresponds to the ``grpc_route`` 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 GrpcRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh - or Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([grpc_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_grpc_route.UpdateGrpcRouteRequest): - request = gcn_grpc_route.UpdateGrpcRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if grpc_route is not None: - request.grpc_route = grpc_route - 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_grpc_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("grpc_route.name", request.grpc_route.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_grpc_route.GrpcRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_grpc_route(self, - request: Optional[Union[grpc_route.DeleteGrpcRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGrpcRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteGrpcRouteRequest, dict]]): - The request object. Request used by the DeleteGrpcRoute - method. - name (:class:`str`): - Required. A name of the GrpcRoute to delete. Must be in - the format ``projects/*/locations/global/grpcRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, grpc_route.DeleteGrpcRouteRequest): - request = grpc_route.DeleteGrpcRouteRequest(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_grpc_route] - - # Certain 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_http_routes(self, - request: Optional[Union[http_route.ListHttpRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListHttpRoutesAsyncPager: - r"""Lists HttpRoute 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_services_v1 - - async def sample_list_http_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListHttpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_http_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListHttpRoutesRequest, dict]]): - The request object. Request used with the ListHttpRoutes - method. - parent (:class:`str`): - Required. The project and location from which the - HttpRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesAsyncPager: - Response returned by the - ListHttpRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, http_route.ListHttpRoutesRequest): - request = http_route.ListHttpRoutesRequest(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_http_routes] - - # 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.ListHttpRoutesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_http_route(self, - request: Optional[Union[http_route.GetHttpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> http_route.HttpRoute: - r"""Gets details of a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetHttpRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_http_route(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetHttpRouteRequest, dict]]): - The request object. Request used by the GetHttpRoute - method. - name (:class:`str`): - Required. A name of the HttpRoute to get. Must be in the - format ``projects/*/locations/global/httpRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.HttpRoute: - HttpRoute is the resource defining - how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, http_route.GetHttpRouteRequest): - request = http_route.GetHttpRouteRequest(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_http_route] - - # Certain 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_http_route(self, - request: Optional[Union[gcn_http_route.CreateHttpRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - http_route: Optional[gcn_http_route.HttpRoute] = None, - http_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new HttpRoute 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_services_v1 - - async def sample_create_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateHttpRouteRequest( - parent="parent_value", - http_route_id="http_route_id_value", - http_route=http_route, - ) - - # Make the request - operation = client.create_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateHttpRouteRequest, dict]]): - The request object. Request used by the HttpRoute method. - parent (:class:`str`): - Required. The parent resource of the HttpRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - http_route (:class:`google.cloud.network_services_v1.types.HttpRoute`): - Required. HttpRoute resource to be - created. - - This corresponds to the ``http_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - http_route_id (:class:`str`): - Required. Short name of the HttpRoute - resource to be created. - - This corresponds to the ``http_route_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([parent, http_route, http_route_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_http_route.CreateHttpRouteRequest): - request = gcn_http_route.CreateHttpRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if http_route is not None: - request.http_route = http_route - if http_route_id is not None: - request.http_route_id = http_route_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_http_route] - - # 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_http_route.HttpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_http_route(self, - request: Optional[Union[gcn_http_route.UpdateHttpRouteRequest, dict]] = None, - *, - http_route: Optional[gcn_http_route.HttpRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateHttpRouteRequest( - http_route=http_route, - ) - - # Make the request - operation = client.update_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateHttpRouteRequest, dict]]): - The request object. Request used by the UpdateHttpRoute - method. - http_route (:class:`google.cloud.network_services_v1.types.HttpRoute`): - Required. Updated HttpRoute resource. - This corresponds to the ``http_route`` 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 HttpRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([http_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_http_route.UpdateHttpRouteRequest): - request = gcn_http_route.UpdateHttpRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if http_route is not None: - request.http_route = http_route - 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_http_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("http_route.name", request.http_route.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_http_route.HttpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_http_route(self, - request: Optional[Union[http_route.DeleteHttpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteHttpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteHttpRouteRequest, dict]]): - The request object. Request used by the DeleteHttpRoute - method. - name (:class:`str`): - Required. A name of the HttpRoute to delete. Must be in - the format ``projects/*/locations/global/httpRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, http_route.DeleteHttpRouteRequest): - request = http_route.DeleteHttpRouteRequest(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_http_route] - - # Certain 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_tcp_routes(self, - request: Optional[Union[tcp_route.ListTcpRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTcpRoutesAsyncPager: - r"""Lists TcpRoute 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_services_v1 - - async def sample_list_tcp_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListTcpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tcp_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListTcpRoutesRequest, dict]]): - The request object. Request used with the ListTcpRoutes - method. - parent (:class:`str`): - Required. The project and location from which the - TcpRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesAsyncPager: - Response returned by the - ListTcpRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tcp_route.ListTcpRoutesRequest): - request = tcp_route.ListTcpRoutesRequest(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_tcp_routes] - - # 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.ListTcpRoutesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_tcp_route(self, - request: Optional[Union[tcp_route.GetTcpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tcp_route.TcpRoute: - r"""Gets details of a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetTcpRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tcp_route(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetTcpRouteRequest, dict]]): - The request object. Request used by the GetTcpRoute - method. - name (:class:`str`): - Required. A name of the TcpRoute to get. Must be in the - format ``projects/*/locations/global/tcpRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.TcpRoute: - TcpRoute is the resource defining how - TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tcp_route.GetTcpRouteRequest): - request = tcp_route.GetTcpRouteRequest(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_tcp_route] - - # Certain 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_tcp_route(self, - request: Optional[Union[gcn_tcp_route.CreateTcpRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, - tcp_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new TcpRoute 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_services_v1 - - async def sample_create_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.CreateTcpRouteRequest( - parent="parent_value", - tcp_route_id="tcp_route_id_value", - tcp_route=tcp_route, - ) - - # Make the request - operation = client.create_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateTcpRouteRequest, dict]]): - The request object. Request used by the TcpRoute method. - parent (:class:`str`): - Required. The parent resource of the TcpRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tcp_route (:class:`google.cloud.network_services_v1.types.TcpRoute`): - Required. TcpRoute resource to be - created. - - This corresponds to the ``tcp_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tcp_route_id (:class:`str`): - Required. Short name of the TcpRoute - resource to be created. - - This corresponds to the ``tcp_route_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([parent, tcp_route, tcp_route_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_tcp_route.CreateTcpRouteRequest): - request = gcn_tcp_route.CreateTcpRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tcp_route is not None: - request.tcp_route = tcp_route - if tcp_route_id is not None: - request.tcp_route_id = tcp_route_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_tcp_route] - - # 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_tcp_route.TcpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_tcp_route(self, - request: Optional[Union[gcn_tcp_route.UpdateTcpRouteRequest, dict]] = None, - *, - tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.UpdateTcpRouteRequest( - tcp_route=tcp_route, - ) - - # Make the request - operation = client.update_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateTcpRouteRequest, dict]]): - The request object. Request used by the UpdateTcpRoute - method. - tcp_route (:class:`google.cloud.network_services_v1.types.TcpRoute`): - Required. Updated TcpRoute resource. - This corresponds to the ``tcp_route`` 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 TcpRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([tcp_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_tcp_route.UpdateTcpRouteRequest): - request = gcn_tcp_route.UpdateTcpRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tcp_route is not None: - request.tcp_route = tcp_route - 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_tcp_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tcp_route.name", request.tcp_route.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_tcp_route.TcpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_tcp_route(self, - request: Optional[Union[tcp_route.DeleteTcpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTcpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteTcpRouteRequest, dict]]): - The request object. Request used by the DeleteTcpRoute - method. - name (:class:`str`): - Required. A name of the TcpRoute to delete. Must be in - the format ``projects/*/locations/global/tcpRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tcp_route.DeleteTcpRouteRequest): - request = tcp_route.DeleteTcpRouteRequest(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_tcp_route] - - # Certain 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_tls_routes(self, - request: Optional[Union[tls_route.ListTlsRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTlsRoutesAsyncPager: - r"""Lists TlsRoute 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_services_v1 - - async def sample_list_tls_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListTlsRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tls_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListTlsRoutesRequest, dict]]): - The request object. Request used with the ListTlsRoutes - method. - parent (:class:`str`): - Required. The project and location from which the - TlsRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesAsyncPager: - Response returned by the - ListTlsRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tls_route.ListTlsRoutesRequest): - request = tls_route.ListTlsRoutesRequest(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_tls_routes] - - # 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.ListTlsRoutesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_tls_route(self, - request: Optional[Union[tls_route.GetTlsRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tls_route.TlsRoute: - r"""Gets details of a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetTlsRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tls_route(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetTlsRouteRequest, dict]]): - The request object. Request used by the GetTlsRoute - method. - name (:class:`str`): - Required. A name of the TlsRoute to get. Must be in the - format ``projects/*/locations/global/tlsRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.TlsRoute: - TlsRoute defines how traffic should - be routed based on SNI and other - matching L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tls_route.GetTlsRouteRequest): - request = tls_route.GetTlsRouteRequest(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_tls_route] - - # Certain 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_tls_route(self, - request: Optional[Union[gcn_tls_route.CreateTlsRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - tls_route: Optional[gcn_tls_route.TlsRoute] = None, - tls_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new TlsRoute 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_services_v1 - - async def sample_create_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.CreateTlsRouteRequest( - parent="parent_value", - tls_route_id="tls_route_id_value", - tls_route=tls_route, - ) - - # Make the request - operation = client.create_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateTlsRouteRequest, dict]]): - The request object. Request used by the TlsRoute method. - parent (:class:`str`): - Required. The parent resource of the TlsRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tls_route (:class:`google.cloud.network_services_v1.types.TlsRoute`): - Required. TlsRoute resource to be - created. - - This corresponds to the ``tls_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tls_route_id (:class:`str`): - Required. Short name of the TlsRoute - resource to be created. - - This corresponds to the ``tls_route_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching - L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, tls_route, tls_route_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_tls_route.CreateTlsRouteRequest): - request = gcn_tls_route.CreateTlsRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tls_route is not None: - request.tls_route = tls_route - if tls_route_id is not None: - request.tls_route_id = tls_route_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_tls_route] - - # 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_tls_route.TlsRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_tls_route(self, - request: Optional[Union[gcn_tls_route.UpdateTlsRouteRequest, dict]] = None, - *, - tls_route: Optional[gcn_tls_route.TlsRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.UpdateTlsRouteRequest( - tls_route=tls_route, - ) - - # Make the request - operation = client.update_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateTlsRouteRequest, dict]]): - The request object. Request used by the UpdateTlsRoute - method. - tls_route (:class:`google.cloud.network_services_v1.types.TlsRoute`): - Required. Updated TlsRoute resource. - This corresponds to the ``tls_route`` 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 TlsRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching - L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tls_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_tls_route.UpdateTlsRouteRequest): - request = gcn_tls_route.UpdateTlsRouteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tls_route is not None: - request.tls_route = tls_route - 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_tls_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tls_route.name", request.tls_route.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_tls_route.TlsRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_tls_route(self, - request: Optional[Union[tls_route.DeleteTlsRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTlsRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteTlsRouteRequest, dict]]): - The request object. Request used by the DeleteTlsRoute - method. - name (:class:`str`): - Required. A name of the TlsRoute to delete. Must be in - the format ``projects/*/locations/global/tlsRoutes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, tls_route.DeleteTlsRouteRequest): - request = tls_route.DeleteTlsRouteRequest(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_tls_route] - - # Certain 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_service_bindings(self, - request: Optional[Union[service_binding.ListServiceBindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServiceBindingsAsyncPager: - r"""Lists ServiceBinding 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_services_v1 - - async def sample_list_service_bindings(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListServiceBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_service_bindings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListServiceBindingsRequest, dict]]): - The request object. Request used with the - ListServiceBindings method. - parent (:class:`str`): - Required. The project and location from which the - ServiceBindings should be listed, specified in the - format ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsAsyncPager: - Response returned by the - ListServiceBindings 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, service_binding.ListServiceBindingsRequest): - request = service_binding.ListServiceBindingsRequest(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_service_bindings] - - # 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.ListServiceBindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service_binding(self, - request: Optional[Union[service_binding.GetServiceBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_binding.ServiceBinding: - r"""Gets details of a single ServiceBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetServiceBindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_service_binding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetServiceBindingRequest, dict]]): - The request object. Request used by the GetServiceBinding - method. - name (:class:`str`): - Required. A name of the ServiceBinding to get. Must be - in the format - ``projects/*/locations/global/serviceBindings/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.ServiceBinding: - ServiceBinding is the resource that - defines a Service Directory Service to - be used in a BackendService 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, service_binding.GetServiceBindingRequest): - request = service_binding.GetServiceBindingRequest(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_service_binding] - - # Certain 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_service_binding(self, - request: Optional[Union[gcn_service_binding.CreateServiceBindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - service_binding: Optional[gcn_service_binding.ServiceBinding] = None, - service_binding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ServiceBinding 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_services_v1 - - async def sample_create_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - service_binding = network_services_v1.ServiceBinding() - service_binding.name = "name_value" - service_binding.service = "service_value" - - request = network_services_v1.CreateServiceBindingRequest( - parent="parent_value", - service_binding_id="service_binding_id_value", - service_binding=service_binding, - ) - - # Make the request - operation = client.create_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateServiceBindingRequest, dict]]): - The request object. Request used by the ServiceBinding - method. - parent (:class:`str`): - Required. The parent resource of the ServiceBinding. - Must be in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_binding (:class:`google.cloud.network_services_v1.types.ServiceBinding`): - Required. ServiceBinding resource to - be created. - - This corresponds to the ``service_binding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_binding_id (:class:`str`): - Required. Short name of the - ServiceBinding resource to be created. - - This corresponds to the ``service_binding_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.ServiceBinding` ServiceBinding is the resource that defines a Service Directory Service to - be used in a BackendService 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. - has_flattened_params = any([parent, service_binding, service_binding_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_service_binding.CreateServiceBindingRequest): - request = gcn_service_binding.CreateServiceBindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service_binding is not None: - request.service_binding = service_binding - if service_binding_id is not None: - request.service_binding_id = service_binding_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_service_binding] - - # 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_service_binding.ServiceBinding, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_service_binding(self, - request: Optional[Union[service_binding.DeleteServiceBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ServiceBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteServiceBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteServiceBindingRequest, dict]]): - The request object. Request used by the - DeleteServiceBinding method. - name (:class:`str`): - Required. A name of the ServiceBinding to delete. Must - be in the format - ``projects/*/locations/global/serviceBindings/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, service_binding.DeleteServiceBindingRequest): - request = service_binding.DeleteServiceBindingRequest(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_service_binding] - - # Certain 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_meshes(self, - request: Optional[Union[mesh.ListMeshesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMeshesAsyncPager: - r"""Lists Meshes 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_services_v1 - - async def sample_list_meshes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListMeshesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_meshes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.ListMeshesRequest, dict]]): - The request object. Request used with the ListMeshes - method. - parent (:class:`str`): - Required. The project and location from which the Meshes - should be listed, specified in the format - ``projects/*/locations/global``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListMeshesAsyncPager: - Response returned by the ListMeshes - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, mesh.ListMeshesRequest): - request = mesh.ListMeshesRequest(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_meshes] - - # 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.ListMeshesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_mesh(self, - request: Optional[Union[mesh.GetMeshRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mesh.Mesh: - r"""Gets details of a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_get_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetMeshRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mesh(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.GetMeshRequest, dict]]): - The request object. Request used by the GetMesh method. - name (:class:`str`): - Required. A name of the Mesh to get. Must be in the - format ``projects/*/locations/global/meshes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.Mesh: - Mesh represents a logical - configuration grouping for workload to - workload communication within a service - mesh. Routes that point to mesh dictate - how requests are routed within this - logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, mesh.GetMeshRequest): - request = mesh.GetMeshRequest(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_mesh] - - # Certain 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_mesh(self, - request: Optional[Union[gcn_mesh.CreateMeshRequest, dict]] = None, - *, - parent: Optional[str] = None, - mesh: Optional[gcn_mesh.Mesh] = None, - mesh_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new Mesh 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_services_v1 - - async def sample_create_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.CreateMeshRequest( - parent="parent_value", - mesh_id="mesh_id_value", - mesh=mesh, - ) - - # Make the request - operation = client.create_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.CreateMeshRequest, dict]]): - The request object. Request used by the CreateMesh - method. - parent (:class:`str`): - Required. The parent resource of the Mesh. Must be in - the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mesh (:class:`google.cloud.network_services_v1.types.Mesh`): - Required. Mesh resource to be - created. - - This corresponds to the ``mesh`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mesh_id (:class:`str`): - Required. Short name of the Mesh - resource to be created. - - This corresponds to the ``mesh_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload - communication within a service mesh. Routes that - point to mesh dictate how requests are routed within - this logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mesh, mesh_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_mesh.CreateMeshRequest): - request = gcn_mesh.CreateMeshRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mesh is not None: - request.mesh = mesh - if mesh_id is not None: - request.mesh_id = mesh_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_mesh] - - # 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_mesh.Mesh, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_mesh(self, - request: Optional[Union[gcn_mesh.UpdateMeshRequest, dict]] = None, - *, - mesh: Optional[gcn_mesh.Mesh] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_update_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.UpdateMeshRequest( - mesh=mesh, - ) - - # Make the request - operation = client.update_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.UpdateMeshRequest, dict]]): - The request object. Request used by the UpdateMesh - method. - mesh (:class:`google.cloud.network_services_v1.types.Mesh`): - Required. Updated Mesh resource. - This corresponds to the ``mesh`` 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 Mesh 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload - communication within a service mesh. Routes that - point to mesh dictate how requests are routed within - this logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mesh, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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_mesh.UpdateMeshRequest): - request = gcn_mesh.UpdateMeshRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mesh is not None: - request.mesh = mesh - 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_mesh] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mesh.name", request.mesh.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_mesh.Mesh, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_mesh(self, - request: Optional[Union[mesh.DeleteMeshRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - async def sample_delete_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteMeshRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_services_v1.types.DeleteMeshRequest, dict]]): - The request object. Request used by the DeleteMesh - method. - name (:class:`str`): - Required. A name of the Mesh to delete. Must be in the - format ``projects/*/locations/global/meshes/*``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, mesh.DeleteMeshRequest): - request = mesh.DeleteMeshRequest(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_mesh] - - # Certain 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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) -> "NetworkServicesAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "NetworkServicesAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py deleted file mode 100644 index b406a45cb1b8..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/client.py +++ /dev/null @@ -1,6202 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.network_services_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, 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_services_v1.services.network_services import pagers -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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 NetworkServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import NetworkServicesGrpcTransport -from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport -from .transports.rest import NetworkServicesRestTransport - - -class NetworkServicesClientMeta(type): - """Metaclass for the NetworkServices 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[NetworkServicesTransport]] - _transport_registry["grpc"] = NetworkServicesGrpcTransport - _transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport - _transport_registry["rest"] = NetworkServicesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[NetworkServicesTransport]: - """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 NetworkServicesClient(metaclass=NetworkServicesClientMeta): - """""" - - @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 = "networkservices.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{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: - NetworkServicesClient: 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: - NetworkServicesClient: 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) -> NetworkServicesTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkServicesTransport: 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 backend_service_path(project: str,location: str,backend_service: str,) -> str: - """Returns a fully-qualified backend_service string.""" - return "projects/{project}/locations/{location}/backendServices/{backend_service}".format(project=project, location=location, backend_service=backend_service, ) - - @staticmethod - def parse_backend_service_path(path: str) -> Dict[str,str]: - """Parses a backend_service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/backendServices/(?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 endpoint_policy_path(project: str,location: str,endpoint_policy: str,) -> str: - """Returns a fully-qualified endpoint_policy string.""" - return "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format(project=project, location=location, endpoint_policy=endpoint_policy, ) - - @staticmethod - def parse_endpoint_policy_path(path: str) -> Dict[str,str]: - """Parses a endpoint_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/endpointPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def gateway_path(project: str,location: str,gateway: str,) -> str: - """Returns a fully-qualified gateway string.""" - return "projects/{project}/locations/{location}/gateways/{gateway}".format(project=project, location=location, gateway=gateway, ) - - @staticmethod - def parse_gateway_path(path: str) -> Dict[str,str]: - """Parses a gateway path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/gateways/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def grpc_route_path(project: str,location: str,grpc_route: str,) -> str: - """Returns a fully-qualified grpc_route string.""" - return "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format(project=project, location=location, grpc_route=grpc_route, ) - - @staticmethod - def parse_grpc_route_path(path: str) -> Dict[str,str]: - """Parses a grpc_route path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/grpcRoutes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def http_route_path(project: str,location: str,http_route: str,) -> str: - """Returns a fully-qualified http_route string.""" - return "projects/{project}/locations/{location}/httpRoutes/{http_route}".format(project=project, location=location, http_route=http_route, ) - - @staticmethod - def parse_http_route_path(path: str) -> Dict[str,str]: - """Parses a http_route path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/httpRoutes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def mesh_path(project: str,location: str,mesh: str,) -> str: - """Returns a fully-qualified mesh string.""" - return "projects/{project}/locations/{location}/meshes/{mesh}".format(project=project, location=location, mesh=mesh, ) - - @staticmethod - def parse_mesh_path(path: str) -> Dict[str,str]: - """Parses a mesh path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/meshes/(?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 service_binding_path(project: str,location: str,service_binding: str,) -> str: - """Returns a fully-qualified service_binding string.""" - return "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format(project=project, location=location, service_binding=service_binding, ) - - @staticmethod - def parse_service_binding_path(path: str) -> Dict[str,str]: - """Parses a service_binding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serviceBindings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tcp_route_path(project: str,location: str,tcp_route: str,) -> str: - """Returns a fully-qualified tcp_route string.""" - return "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format(project=project, location=location, tcp_route=tcp_route, ) - - @staticmethod - def parse_tcp_route_path(path: str) -> Dict[str,str]: - """Parses a tcp_route path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tcpRoutes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tls_route_path(project: str,location: str,tls_route: str,) -> str: - """Returns a fully-qualified tls_route string.""" - return "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format(project=project, location=location, tls_route=tls_route, ) - - @staticmethod - def parse_tls_route_path(path: str) -> Dict[str,str]: - """Parses a tls_route path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tlsRoutes/(?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 = NetworkServicesClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = NetworkServicesClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = NetworkServicesClient._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 = NetworkServicesClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - NetworkServicesClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @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, NetworkServicesTransport, Callable[..., NetworkServicesTransport]]] = 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 services 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,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): - 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 NetworkServicesTransport 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 = NetworkServicesClient._read_environment_variables() - self._client_cert_source = NetworkServicesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = NetworkServicesClient._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 - - 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, NetworkServicesTransport) - if transport_provided: - # transport is a NetworkServicesTransport 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(NetworkServicesTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - NetworkServicesClient._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[NetworkServicesTransport], Callable[..., NetworkServicesTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., NetworkServicesTransport], 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, - ) - - def list_endpoint_policies(self, - request: Optional[Union[endpoint_policy.ListEndpointPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEndpointPoliciesPager: - r"""Lists EndpointPolicies 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_services_v1 - - def sample_list_endpoint_policies(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListEndpointPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_endpoint_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListEndpointPoliciesRequest, dict]): - The request object. Request used with the - ListEndpointPolicies method. - parent (str): - Required. The project and location from which the - EndpointPolicies should be listed, specified in the - format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesPager: - Response returned by the - ListEndpointPolicies 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, endpoint_policy.ListEndpointPoliciesRequest): - request = endpoint_policy.ListEndpointPoliciesRequest(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_endpoint_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.ListEndpointPoliciesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_endpoint_policy(self, - request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> endpoint_policy.EndpointPolicy: - r"""Gets details of a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_endpoint_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetEndpointPolicyRequest, dict]): - The request object. Request used with the - GetEndpointPolicy method. - name (str): - Required. A name of the EndpointPolicy to get. Must be - in the format - ``projects/*/locations/global/endpointPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.EndpointPolicy: - EndpointPolicy is a resource that - helps apply desired configuration on the - endpoints that match specific criteria. - For example, this resource can be used - to apply "authentication config" an all - endpoints that serve on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, endpoint_policy.GetEndpointPolicyRequest): - request = endpoint_policy.GetEndpointPolicyRequest(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_endpoint_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_endpoint_policy(self, - request: Optional[Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, - endpoint_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new EndpointPolicy 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_services_v1 - - def sample_create_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.CreateEndpointPolicyRequest( - parent="parent_value", - endpoint_policy_id="endpoint_policy_id_value", - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.create_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateEndpointPolicyRequest, dict]): - The request object. Request used with the - CreateEndpointPolicy method. - parent (str): - Required. The parent resource of the EndpointPolicy. - Must be in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): - Required. EndpointPolicy resource to - be created. - - This corresponds to the ``endpoint_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - endpoint_policy_id (str): - Required. Short name of the - EndpointPolicy resource to be created. - E.g. "CustomECS". - - This corresponds to the ``endpoint_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration - on the endpoints that match specific criteria. For - example, this resource can be used to apply - "authentication config" an all endpoints that serve - on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, endpoint_policy, endpoint_policy_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_endpoint_policy.CreateEndpointPolicyRequest): - request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if endpoint_policy is not None: - request.endpoint_policy = endpoint_policy - if endpoint_policy_id is not None: - request.endpoint_policy_id = endpoint_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_endpoint_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_endpoint_policy.EndpointPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_endpoint_policy(self, - request: Optional[Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict]] = None, - *, - endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.UpdateEndpointPolicyRequest( - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.update_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest, dict]): - The request object. Request used with the - UpdateEndpointPolicy method. - endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): - Required. Updated EndpointPolicy - resource. - - This corresponds to the ``endpoint_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 EndpointPolicy 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration - on the endpoints that match specific criteria. For - example, this resource can be used to apply - "authentication config" an all endpoints that serve - on port 8080. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([endpoint_policy, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_endpoint_policy.UpdateEndpointPolicyRequest): - request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if endpoint_policy is not None: - request.endpoint_policy = endpoint_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_endpoint_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("endpoint_policy.name", request.endpoint_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_endpoint_policy.EndpointPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_endpoint_policy(self, - request: Optional[Union[endpoint_policy.DeleteEndpointPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single EndpointPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest, dict]): - The request object. Request used with the - DeleteEndpointPolicy method. - name (str): - Required. A name of the EndpointPolicy to delete. Must - be in the format - ``projects/*/locations/global/endpointPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, endpoint_policy.DeleteEndpointPolicyRequest): - request = endpoint_policy.DeleteEndpointPolicyRequest(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_endpoint_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_gateways(self, - request: Optional[Union[gateway.ListGatewaysRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGatewaysPager: - r"""Lists Gateways 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_services_v1 - - def sample_list_gateways(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListGatewaysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gateways(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListGatewaysRequest, dict]): - The request object. Request used with the ListGateways - method. - parent (str): - Required. The project and location from which the - Gateways should be listed, specified in the format - ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysPager: - Response returned by the ListGateways - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, gateway.ListGatewaysRequest): - request = gateway.ListGatewaysRequest(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_gateways] - - # 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.ListGatewaysPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_gateway(self, - request: Optional[Union[gateway.GetGatewayRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gateway.Gateway: - r"""Gets details of a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetGatewayRequest( - name="name_value", - ) - - # Make the request - response = client.get_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetGatewayRequest, dict]): - The request object. Request used by the GetGateway - method. - name (str): - Required. A name of the Gateway to get. Must be in the - format ``projects/*/locations/*/gateways/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.Gateway: - Gateway represents the configuration - for a proxy, typically a load balancer. - It captures the ip:port over which the - services are exposed by the proxy, along - with any policy configurations. Routes - have reference to to Gateways to dictate - how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, gateway.GetGatewayRequest): - request = gateway.GetGatewayRequest(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_gateway] - - # Certain 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_gateway(self, - request: Optional[Union[gcn_gateway.CreateGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway: Optional[gcn_gateway.Gateway] = None, - gateway_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new Gateway 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_services_v1 - - def sample_create_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.CreateGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - gateway=gateway, - ) - - # Make the request - operation = client.create_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateGatewayRequest, dict]): - The request object. Request used by the CreateGateway - method. - parent (str): - Required. The parent resource of the Gateway. Must be in - the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway (google.cloud.network_services_v1.types.Gateway): - Required. Gateway resource to be - created. - - This corresponds to the ``gateway`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (str): - Required. Short name of the Gateway - resource to be created. - - This corresponds to the ``gateway_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. - It captures the ip:port over which the services are - exposed by the proxy, along with any policy - configurations. Routes have reference to to Gateways - to dictate how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway, gateway_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_gateway.CreateGatewayRequest): - request = gcn_gateway.CreateGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway is not None: - request.gateway = gateway - if gateway_id is not None: - request.gateway_id = gateway_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_gateway] - - # 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_gateway.Gateway, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_gateway(self, - request: Optional[Union[gcn_gateway.UpdateGatewayRequest, dict]] = None, - *, - gateway: Optional[gcn_gateway.Gateway] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.UpdateGatewayRequest( - gateway=gateway, - ) - - # Make the request - operation = client.update_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateGatewayRequest, dict]): - The request object. Request used by the UpdateGateway - method. - gateway (google.cloud.network_services_v1.types.Gateway): - Required. Updated Gateway resource. - This corresponds to the ``gateway`` 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 Gateway 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Gateway` Gateway represents the configuration for a proxy, typically a load balancer. - It captures the ip:port over which the services are - exposed by the proxy, along with any policy - configurations. Routes have reference to to Gateways - to dictate how requests should be routed by this - Gateway. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([gateway, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_gateway.UpdateGatewayRequest): - request = gcn_gateway.UpdateGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if gateway is not None: - request.gateway = gateway - 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_gateway] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("gateway.name", request.gateway.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_gateway.Gateway, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_gateway(self, - request: Optional[Union[gateway.DeleteGatewayRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single Gateway. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGatewayRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteGatewayRequest, dict]): - The request object. Request used by the DeleteGateway - method. - name (str): - Required. A name of the Gateway to delete. Must be in - the format ``projects/*/locations/*/gateways/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, gateway.DeleteGatewayRequest): - request = gateway.DeleteGatewayRequest(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_gateway] - - # Certain 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_grpc_routes(self, - request: Optional[Union[grpc_route.ListGrpcRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGrpcRoutesPager: - r"""Lists GrpcRoutes 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_services_v1 - - def sample_list_grpc_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListGrpcRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_grpc_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListGrpcRoutesRequest, dict]): - The request object. Request used with the ListGrpcRoutes - method. - parent (str): - Required. The project and location from which the - GrpcRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesPager: - Response returned by the - ListGrpcRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, grpc_route.ListGrpcRoutesRequest): - request = grpc_route.ListGrpcRoutesRequest(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_grpc_routes] - - # 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.ListGrpcRoutesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_grpc_route(self, - request: Optional[Union[grpc_route.GetGrpcRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> grpc_route.GrpcRoute: - r"""Gets details of a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetGrpcRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_grpc_route(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetGrpcRouteRequest, dict]): - The request object. Request used by the GetGrpcRoute - method. - name (str): - Required. A name of the GrpcRoute to get. Must be in the - format ``projects/*/locations/global/grpcRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.GrpcRoute: - GrpcRoute is the resource defining - how gRPC traffic routed by a Mesh or - Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, grpc_route.GetGrpcRouteRequest): - request = grpc_route.GetGrpcRouteRequest(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_grpc_route] - - # Certain 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_grpc_route(self, - request: Optional[Union[gcn_grpc_route.CreateGrpcRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, - grpc_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new GrpcRoute 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_services_v1 - - def sample_create_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateGrpcRouteRequest( - parent="parent_value", - grpc_route_id="grpc_route_id_value", - grpc_route=grpc_route, - ) - - # Make the request - operation = client.create_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateGrpcRouteRequest, dict]): - The request object. Request used by the CreateGrpcRoute - method. - parent (str): - Required. The parent resource of the GrpcRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - grpc_route (google.cloud.network_services_v1.types.GrpcRoute): - Required. GrpcRoute resource to be - created. - - This corresponds to the ``grpc_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - grpc_route_id (str): - Required. Short name of the GrpcRoute - resource to be created. - - This corresponds to the ``grpc_route_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh - or Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, grpc_route, grpc_route_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_grpc_route.CreateGrpcRouteRequest): - request = gcn_grpc_route.CreateGrpcRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if grpc_route is not None: - request.grpc_route = grpc_route - if grpc_route_id is not None: - request.grpc_route_id = grpc_route_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_grpc_route] - - # 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_grpc_route.GrpcRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_grpc_route(self, - request: Optional[Union[gcn_grpc_route.UpdateGrpcRouteRequest, dict]] = None, - *, - grpc_route: Optional[gcn_grpc_route.GrpcRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateGrpcRouteRequest( - grpc_route=grpc_route, - ) - - # Make the request - operation = client.update_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateGrpcRouteRequest, dict]): - The request object. Request used by the UpdateGrpcRoute - method. - grpc_route (google.cloud.network_services_v1.types.GrpcRoute): - Required. Updated GrpcRoute resource. - This corresponds to the ``grpc_route`` 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 GrpcRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.GrpcRoute` GrpcRoute is the resource defining how gRPC traffic routed by a Mesh - or Gateway resource is routed. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([grpc_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_grpc_route.UpdateGrpcRouteRequest): - request = gcn_grpc_route.UpdateGrpcRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if grpc_route is not None: - request.grpc_route = grpc_route - 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_grpc_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("grpc_route.name", request.grpc_route.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_grpc_route.GrpcRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_grpc_route(self, - request: Optional[Union[grpc_route.DeleteGrpcRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single GrpcRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGrpcRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteGrpcRouteRequest, dict]): - The request object. Request used by the DeleteGrpcRoute - method. - name (str): - Required. A name of the GrpcRoute to delete. Must be in - the format ``projects/*/locations/global/grpcRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, grpc_route.DeleteGrpcRouteRequest): - request = grpc_route.DeleteGrpcRouteRequest(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_grpc_route] - - # Certain 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_http_routes(self, - request: Optional[Union[http_route.ListHttpRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListHttpRoutesPager: - r"""Lists HttpRoute 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_services_v1 - - def sample_list_http_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListHttpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_http_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListHttpRoutesRequest, dict]): - The request object. Request used with the ListHttpRoutes - method. - parent (str): - Required. The project and location from which the - HttpRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesPager: - Response returned by the - ListHttpRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, http_route.ListHttpRoutesRequest): - request = http_route.ListHttpRoutesRequest(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_http_routes] - - # 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.ListHttpRoutesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_http_route(self, - request: Optional[Union[http_route.GetHttpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> http_route.HttpRoute: - r"""Gets details of a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetHttpRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_http_route(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetHttpRouteRequest, dict]): - The request object. Request used by the GetHttpRoute - method. - name (str): - Required. A name of the HttpRoute to get. Must be in the - format ``projects/*/locations/global/httpRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.HttpRoute: - HttpRoute is the resource defining - how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, http_route.GetHttpRouteRequest): - request = http_route.GetHttpRouteRequest(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_http_route] - - # Certain 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_http_route(self, - request: Optional[Union[gcn_http_route.CreateHttpRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - http_route: Optional[gcn_http_route.HttpRoute] = None, - http_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new HttpRoute 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_services_v1 - - def sample_create_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateHttpRouteRequest( - parent="parent_value", - http_route_id="http_route_id_value", - http_route=http_route, - ) - - # Make the request - operation = client.create_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateHttpRouteRequest, dict]): - The request object. Request used by the HttpRoute method. - parent (str): - Required. The parent resource of the HttpRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - http_route (google.cloud.network_services_v1.types.HttpRoute): - Required. HttpRoute resource to be - created. - - This corresponds to the ``http_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - http_route_id (str): - Required. Short name of the HttpRoute - resource to be created. - - This corresponds to the ``http_route_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([parent, http_route, http_route_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_http_route.CreateHttpRouteRequest): - request = gcn_http_route.CreateHttpRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if http_route is not None: - request.http_route = http_route - if http_route_id is not None: - request.http_route_id = http_route_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_http_route] - - # 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_http_route.HttpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_http_route(self, - request: Optional[Union[gcn_http_route.UpdateHttpRouteRequest, dict]] = None, - *, - http_route: Optional[gcn_http_route.HttpRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateHttpRouteRequest( - http_route=http_route, - ) - - # Make the request - operation = client.update_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateHttpRouteRequest, dict]): - The request object. Request used by the UpdateHttpRoute - method. - http_route (google.cloud.network_services_v1.types.HttpRoute): - Required. Updated HttpRoute resource. - This corresponds to the ``http_route`` 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 HttpRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.HttpRoute` HttpRoute is the resource defining how HTTP traffic should be routed by a - Mesh or Gateway 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. - has_flattened_params = any([http_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_http_route.UpdateHttpRouteRequest): - request = gcn_http_route.UpdateHttpRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if http_route is not None: - request.http_route = http_route - 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_http_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("http_route.name", request.http_route.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_http_route.HttpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_http_route(self, - request: Optional[Union[http_route.DeleteHttpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single HttpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteHttpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteHttpRouteRequest, dict]): - The request object. Request used by the DeleteHttpRoute - method. - name (str): - Required. A name of the HttpRoute to delete. Must be in - the format ``projects/*/locations/global/httpRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, http_route.DeleteHttpRouteRequest): - request = http_route.DeleteHttpRouteRequest(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_http_route] - - # Certain 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_tcp_routes(self, - request: Optional[Union[tcp_route.ListTcpRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTcpRoutesPager: - r"""Lists TcpRoute 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_services_v1 - - def sample_list_tcp_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListTcpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tcp_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListTcpRoutesRequest, dict]): - The request object. Request used with the ListTcpRoutes - method. - parent (str): - Required. The project and location from which the - TcpRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesPager: - Response returned by the - ListTcpRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tcp_route.ListTcpRoutesRequest): - request = tcp_route.ListTcpRoutesRequest(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_tcp_routes] - - # 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.ListTcpRoutesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_tcp_route(self, - request: Optional[Union[tcp_route.GetTcpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tcp_route.TcpRoute: - r"""Gets details of a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetTcpRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_tcp_route(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetTcpRouteRequest, dict]): - The request object. Request used by the GetTcpRoute - method. - name (str): - Required. A name of the TcpRoute to get. Must be in the - format ``projects/*/locations/global/tcpRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.TcpRoute: - TcpRoute is the resource defining how - TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tcp_route.GetTcpRouteRequest): - request = tcp_route.GetTcpRouteRequest(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_tcp_route] - - # Certain 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_tcp_route(self, - request: Optional[Union[gcn_tcp_route.CreateTcpRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, - tcp_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new TcpRoute 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_services_v1 - - def sample_create_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.CreateTcpRouteRequest( - parent="parent_value", - tcp_route_id="tcp_route_id_value", - tcp_route=tcp_route, - ) - - # Make the request - operation = client.create_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateTcpRouteRequest, dict]): - The request object. Request used by the TcpRoute method. - parent (str): - Required. The parent resource of the TcpRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tcp_route (google.cloud.network_services_v1.types.TcpRoute): - Required. TcpRoute resource to be - created. - - This corresponds to the ``tcp_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tcp_route_id (str): - Required. Short name of the TcpRoute - resource to be created. - - This corresponds to the ``tcp_route_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([parent, tcp_route, tcp_route_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_tcp_route.CreateTcpRouteRequest): - request = gcn_tcp_route.CreateTcpRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tcp_route is not None: - request.tcp_route = tcp_route - if tcp_route_id is not None: - request.tcp_route_id = tcp_route_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tcp_route] - - # 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_tcp_route.TcpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_tcp_route(self, - request: Optional[Union[gcn_tcp_route.UpdateTcpRouteRequest, dict]] = None, - *, - tcp_route: Optional[gcn_tcp_route.TcpRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.UpdateTcpRouteRequest( - tcp_route=tcp_route, - ) - - # Make the request - operation = client.update_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateTcpRouteRequest, dict]): - The request object. Request used by the UpdateTcpRoute - method. - tcp_route (google.cloud.network_services_v1.types.TcpRoute): - Required. Updated TcpRoute resource. - This corresponds to the ``tcp_route`` 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 TcpRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TcpRoute` TcpRoute is the resource defining how TCP traffic should be routed by a - Mesh/Gateway 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. - has_flattened_params = any([tcp_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_tcp_route.UpdateTcpRouteRequest): - request = gcn_tcp_route.UpdateTcpRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tcp_route is not None: - request.tcp_route = tcp_route - 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_tcp_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tcp_route.name", request.tcp_route.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_tcp_route.TcpRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_tcp_route(self, - request: Optional[Union[tcp_route.DeleteTcpRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single TcpRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTcpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteTcpRouteRequest, dict]): - The request object. Request used by the DeleteTcpRoute - method. - name (str): - Required. A name of the TcpRoute to delete. Must be in - the format ``projects/*/locations/global/tcpRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tcp_route.DeleteTcpRouteRequest): - request = tcp_route.DeleteTcpRouteRequest(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_tcp_route] - - # Certain 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_tls_routes(self, - request: Optional[Union[tls_route.ListTlsRoutesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTlsRoutesPager: - r"""Lists TlsRoute 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_services_v1 - - def sample_list_tls_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListTlsRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tls_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListTlsRoutesRequest, dict]): - The request object. Request used with the ListTlsRoutes - method. - parent (str): - Required. The project and location from which the - TlsRoutes should be listed, specified in the format - ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesPager: - Response returned by the - ListTlsRoutes 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tls_route.ListTlsRoutesRequest): - request = tls_route.ListTlsRoutesRequest(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_tls_routes] - - # 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.ListTlsRoutesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_tls_route(self, - request: Optional[Union[tls_route.GetTlsRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tls_route.TlsRoute: - r"""Gets details of a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetTlsRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_tls_route(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetTlsRouteRequest, dict]): - The request object. Request used by the GetTlsRoute - method. - name (str): - Required. A name of the TlsRoute to get. Must be in the - format ``projects/*/locations/global/tlsRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.TlsRoute: - TlsRoute defines how traffic should - be routed based on SNI and other - matching L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tls_route.GetTlsRouteRequest): - request = tls_route.GetTlsRouteRequest(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_tls_route] - - # Certain 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_tls_route(self, - request: Optional[Union[gcn_tls_route.CreateTlsRouteRequest, dict]] = None, - *, - parent: Optional[str] = None, - tls_route: Optional[gcn_tls_route.TlsRoute] = None, - tls_route_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new TlsRoute 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_services_v1 - - def sample_create_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.CreateTlsRouteRequest( - parent="parent_value", - tls_route_id="tls_route_id_value", - tls_route=tls_route, - ) - - # Make the request - operation = client.create_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateTlsRouteRequest, dict]): - The request object. Request used by the TlsRoute method. - parent (str): - Required. The parent resource of the TlsRoute. Must be - in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tls_route (google.cloud.network_services_v1.types.TlsRoute): - Required. TlsRoute resource to be - created. - - This corresponds to the ``tls_route`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tls_route_id (str): - Required. Short name of the TlsRoute - resource to be created. - - This corresponds to the ``tls_route_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching - L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, tls_route, tls_route_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_tls_route.CreateTlsRouteRequest): - request = gcn_tls_route.CreateTlsRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tls_route is not None: - request.tls_route = tls_route - if tls_route_id is not None: - request.tls_route_id = tls_route_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tls_route] - - # 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_tls_route.TlsRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_tls_route(self, - request: Optional[Union[gcn_tls_route.UpdateTlsRouteRequest, dict]] = None, - *, - tls_route: Optional[gcn_tls_route.TlsRoute] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.UpdateTlsRouteRequest( - tls_route=tls_route, - ) - - # Make the request - operation = client.update_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateTlsRouteRequest, dict]): - The request object. Request used by the UpdateTlsRoute - method. - tls_route (google.cloud.network_services_v1.types.TlsRoute): - Required. Updated TlsRoute resource. - This corresponds to the ``tls_route`` 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 TlsRoute 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.TlsRoute` TlsRoute defines how traffic should be routed based on SNI and other matching - L3 attributes. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tls_route, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_tls_route.UpdateTlsRouteRequest): - request = gcn_tls_route.UpdateTlsRouteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tls_route is not None: - request.tls_route = tls_route - 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_tls_route] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tls_route.name", request.tls_route.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_tls_route.TlsRoute, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_tls_route(self, - request: Optional[Union[tls_route.DeleteTlsRouteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single TlsRoute. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTlsRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteTlsRouteRequest, dict]): - The request object. Request used by the DeleteTlsRoute - method. - name (str): - Required. A name of the TlsRoute to delete. Must be in - the format ``projects/*/locations/global/tlsRoutes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, tls_route.DeleteTlsRouteRequest): - request = tls_route.DeleteTlsRouteRequest(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_tls_route] - - # Certain 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_service_bindings(self, - request: Optional[Union[service_binding.ListServiceBindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServiceBindingsPager: - r"""Lists ServiceBinding 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_services_v1 - - def sample_list_service_bindings(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListServiceBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_service_bindings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListServiceBindingsRequest, dict]): - The request object. Request used with the - ListServiceBindings method. - parent (str): - Required. The project and location from which the - ServiceBindings should be listed, specified in the - format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsPager: - Response returned by the - ListServiceBindings 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, service_binding.ListServiceBindingsRequest): - request = service_binding.ListServiceBindingsRequest(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_service_bindings] - - # 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.ListServiceBindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service_binding(self, - request: Optional[Union[service_binding.GetServiceBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_binding.ServiceBinding: - r"""Gets details of a single ServiceBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetServiceBindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_service_binding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetServiceBindingRequest, dict]): - The request object. Request used by the GetServiceBinding - method. - name (str): - Required. A name of the ServiceBinding to get. Must be - in the format - ``projects/*/locations/global/serviceBindings/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.ServiceBinding: - ServiceBinding is the resource that - defines a Service Directory Service to - be used in a BackendService 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, service_binding.GetServiceBindingRequest): - request = service_binding.GetServiceBindingRequest(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_service_binding] - - # Certain 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_service_binding(self, - request: Optional[Union[gcn_service_binding.CreateServiceBindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - service_binding: Optional[gcn_service_binding.ServiceBinding] = None, - service_binding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new ServiceBinding 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_services_v1 - - def sample_create_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - service_binding = network_services_v1.ServiceBinding() - service_binding.name = "name_value" - service_binding.service = "service_value" - - request = network_services_v1.CreateServiceBindingRequest( - parent="parent_value", - service_binding_id="service_binding_id_value", - service_binding=service_binding, - ) - - # Make the request - operation = client.create_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateServiceBindingRequest, dict]): - The request object. Request used by the ServiceBinding - method. - parent (str): - Required. The parent resource of the ServiceBinding. - Must be in the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_binding (google.cloud.network_services_v1.types.ServiceBinding): - Required. ServiceBinding resource to - be created. - - This corresponds to the ``service_binding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_binding_id (str): - Required. Short name of the - ServiceBinding resource to be created. - - This corresponds to the ``service_binding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.ServiceBinding` ServiceBinding is the resource that defines a Service Directory Service to - be used in a BackendService 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. - has_flattened_params = any([parent, service_binding, service_binding_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_service_binding.CreateServiceBindingRequest): - request = gcn_service_binding.CreateServiceBindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if service_binding is not None: - request.service_binding = service_binding - if service_binding_id is not None: - request.service_binding_id = service_binding_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service_binding] - - # 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_service_binding.ServiceBinding, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_service_binding(self, - request: Optional[Union[service_binding.DeleteServiceBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single ServiceBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteServiceBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteServiceBindingRequest, dict]): - The request object. Request used by the - DeleteServiceBinding method. - name (str): - Required. A name of the ServiceBinding to delete. Must - be in the format - ``projects/*/locations/global/serviceBindings/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, service_binding.DeleteServiceBindingRequest): - request = service_binding.DeleteServiceBindingRequest(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_service_binding] - - # Certain 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_meshes(self, - request: Optional[Union[mesh.ListMeshesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMeshesPager: - r"""Lists Meshes 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_services_v1 - - def sample_list_meshes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListMeshesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_meshes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.ListMeshesRequest, dict]): - The request object. Request used with the ListMeshes - method. - parent (str): - Required. The project and location from which the Meshes - should be listed, specified in the format - ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.services.network_services.pagers.ListMeshesPager: - Response returned by the ListMeshes - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, mesh.ListMeshesRequest): - request = mesh.ListMeshesRequest(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_meshes] - - # 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.ListMeshesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_mesh(self, - request: Optional[Union[mesh.GetMeshRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mesh.Mesh: - r"""Gets details of a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_get_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetMeshRequest( - name="name_value", - ) - - # Make the request - response = client.get_mesh(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.GetMeshRequest, dict]): - The request object. Request used by the GetMesh method. - name (str): - Required. A name of the Mesh to get. Must be in the - format ``projects/*/locations/global/meshes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.network_services_v1.types.Mesh: - Mesh represents a logical - configuration grouping for workload to - workload communication within a service - mesh. Routes that point to mesh dictate - how requests are routed within this - logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, mesh.GetMeshRequest): - request = mesh.GetMeshRequest(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_mesh] - - # Certain 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_mesh(self, - request: Optional[Union[gcn_mesh.CreateMeshRequest, dict]] = None, - *, - parent: Optional[str] = None, - mesh: Optional[gcn_mesh.Mesh] = None, - mesh_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new Mesh 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_services_v1 - - def sample_create_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.CreateMeshRequest( - parent="parent_value", - mesh_id="mesh_id_value", - mesh=mesh, - ) - - # Make the request - operation = client.create_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.CreateMeshRequest, dict]): - The request object. Request used by the CreateMesh - method. - parent (str): - Required. The parent resource of the Mesh. Must be in - the format ``projects/*/locations/global``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mesh (google.cloud.network_services_v1.types.Mesh): - Required. Mesh resource to be - created. - - This corresponds to the ``mesh`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mesh_id (str): - Required. Short name of the Mesh - resource to be created. - - This corresponds to the ``mesh_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload - communication within a service mesh. Routes that - point to mesh dictate how requests are routed within - this logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mesh, mesh_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_mesh.CreateMeshRequest): - request = gcn_mesh.CreateMeshRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mesh is not None: - request.mesh = mesh - if mesh_id is not None: - request.mesh_id = mesh_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_mesh] - - # 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_mesh.Mesh, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_mesh(self, - request: Optional[Union[gcn_mesh.UpdateMeshRequest, dict]] = None, - *, - mesh: Optional[gcn_mesh.Mesh] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_update_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.UpdateMeshRequest( - mesh=mesh, - ) - - # Make the request - operation = client.update_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.UpdateMeshRequest, dict]): - The request object. Request used by the UpdateMesh - method. - mesh (google.cloud.network_services_v1.types.Mesh): - Required. Updated Mesh resource. - This corresponds to the ``mesh`` 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 Mesh 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_services_v1.types.Mesh` Mesh represents a logical configuration grouping for workload to workload - communication within a service mesh. Routes that - point to mesh dictate how requests are routed within - this logical mesh boundary. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mesh, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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_mesh.UpdateMeshRequest): - request = gcn_mesh.UpdateMeshRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mesh is not None: - request.mesh = mesh - 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_mesh] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mesh.name", request.mesh.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_mesh.Mesh, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_mesh(self, - request: Optional[Union[mesh.DeleteMeshRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single Mesh. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_services_v1 - - def sample_delete_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteMeshRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_services_v1.types.DeleteMeshRequest, dict]): - The request object. Request used by the DeleteMesh - method. - name (str): - Required. A name of the Mesh to delete. Must be in the - format ``projects/*/locations/global/meshes/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, mesh.DeleteMeshRequest): - request = mesh.DeleteMeshRequest(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_mesh] - - # Certain 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) -> "NetworkServicesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # 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 get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "NetworkServicesClient", -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py deleted file mode 100644 index 221631ee752d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/pagers.py +++ /dev/null @@ -1,993 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tls_route - - -class ListEndpointPoliciesPager: - """A pager for iterating through ``list_endpoint_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``endpoint_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEndpointPolicies`` requests and continue to iterate - through the ``endpoint_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` - 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[..., endpoint_policy.ListEndpointPoliciesResponse], - request: endpoint_policy.ListEndpointPoliciesRequest, - response: endpoint_policy.ListEndpointPoliciesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListEndpointPoliciesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListEndpointPoliciesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = endpoint_policy.ListEndpointPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[endpoint_policy.ListEndpointPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[endpoint_policy.EndpointPolicy]: - for page in self.pages: - yield from page.endpoint_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEndpointPoliciesAsyncPager: - """A pager for iterating through ``list_endpoint_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``endpoint_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEndpointPolicies`` requests and continue to iterate - through the ``endpoint_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListEndpointPoliciesResponse` - 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[endpoint_policy.ListEndpointPoliciesResponse]], - request: endpoint_policy.ListEndpointPoliciesRequest, - response: endpoint_policy.ListEndpointPoliciesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListEndpointPoliciesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListEndpointPoliciesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = endpoint_policy.ListEndpointPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[endpoint_policy.ListEndpointPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[endpoint_policy.EndpointPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.endpoint_policies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGatewaysPager: - """A pager for iterating through ``list_gateways`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` object, and - provides an ``__iter__`` method to iterate through its - ``gateways`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListGateways`` requests and continue to iterate - through the ``gateways`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` - 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[..., gateway.ListGatewaysResponse], - request: gateway.ListGatewaysRequest, - response: gateway.ListGatewaysResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListGatewaysRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListGatewaysResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = gateway.ListGatewaysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[gateway.ListGatewaysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[gateway.Gateway]: - for page in self.pages: - yield from page.gateways - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGatewaysAsyncPager: - """A pager for iterating through ``list_gateways`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``gateways`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListGateways`` requests and continue to iterate - through the ``gateways`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListGatewaysResponse` - 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[gateway.ListGatewaysResponse]], - request: gateway.ListGatewaysRequest, - response: gateway.ListGatewaysResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListGatewaysRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListGatewaysResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = gateway.ListGatewaysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[gateway.ListGatewaysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[gateway.Gateway]: - async def async_generator(): - async for page in self.pages: - for response in page.gateways: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGrpcRoutesPager: - """A pager for iterating through ``list_grpc_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``grpc_routes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListGrpcRoutes`` requests and continue to iterate - through the ``grpc_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` - 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[..., grpc_route.ListGrpcRoutesResponse], - request: grpc_route.ListGrpcRoutesRequest, - response: grpc_route.ListGrpcRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListGrpcRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListGrpcRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = grpc_route.ListGrpcRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[grpc_route.ListGrpcRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[grpc_route.GrpcRoute]: - for page in self.pages: - yield from page.grpc_routes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGrpcRoutesAsyncPager: - """A pager for iterating through ``list_grpc_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``grpc_routes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListGrpcRoutes`` requests and continue to iterate - through the ``grpc_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListGrpcRoutesResponse` - 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[grpc_route.ListGrpcRoutesResponse]], - request: grpc_route.ListGrpcRoutesRequest, - response: grpc_route.ListGrpcRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListGrpcRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListGrpcRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = grpc_route.ListGrpcRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[grpc_route.ListGrpcRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[grpc_route.GrpcRoute]: - async def async_generator(): - async for page in self.pages: - for response in page.grpc_routes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListHttpRoutesPager: - """A pager for iterating through ``list_http_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``http_routes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListHttpRoutes`` requests and continue to iterate - through the ``http_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` - 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[..., http_route.ListHttpRoutesResponse], - request: http_route.ListHttpRoutesRequest, - response: http_route.ListHttpRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListHttpRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListHttpRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = http_route.ListHttpRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[http_route.ListHttpRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[http_route.HttpRoute]: - for page in self.pages: - yield from page.http_routes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListHttpRoutesAsyncPager: - """A pager for iterating through ``list_http_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``http_routes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListHttpRoutes`` requests and continue to iterate - through the ``http_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListHttpRoutesResponse` - 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[http_route.ListHttpRoutesResponse]], - request: http_route.ListHttpRoutesRequest, - response: http_route.ListHttpRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListHttpRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListHttpRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = http_route.ListHttpRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[http_route.ListHttpRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[http_route.HttpRoute]: - async def async_generator(): - async for page in self.pages: - for response in page.http_routes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTcpRoutesPager: - """A pager for iterating through ``list_tcp_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tcp_routes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTcpRoutes`` requests and continue to iterate - through the ``tcp_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` - 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[..., tcp_route.ListTcpRoutesResponse], - request: tcp_route.ListTcpRoutesRequest, - response: tcp_route.ListTcpRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListTcpRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListTcpRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tcp_route.ListTcpRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[tcp_route.ListTcpRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tcp_route.TcpRoute]: - for page in self.pages: - yield from page.tcp_routes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTcpRoutesAsyncPager: - """A pager for iterating through ``list_tcp_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tcp_routes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTcpRoutes`` requests and continue to iterate - through the ``tcp_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListTcpRoutesResponse` - 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[tcp_route.ListTcpRoutesResponse]], - request: tcp_route.ListTcpRoutesRequest, - response: tcp_route.ListTcpRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListTcpRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListTcpRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tcp_route.ListTcpRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[tcp_route.ListTcpRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[tcp_route.TcpRoute]: - async def async_generator(): - async for page in self.pages: - for response in page.tcp_routes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTlsRoutesPager: - """A pager for iterating through ``list_tls_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tls_routes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTlsRoutes`` requests and continue to iterate - through the ``tls_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` - 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[..., tls_route.ListTlsRoutesResponse], - request: tls_route.ListTlsRoutesRequest, - response: tls_route.ListTlsRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListTlsRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListTlsRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tls_route.ListTlsRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[tls_route.ListTlsRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tls_route.TlsRoute]: - for page in self.pages: - yield from page.tls_routes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTlsRoutesAsyncPager: - """A pager for iterating through ``list_tls_routes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tls_routes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTlsRoutes`` requests and continue to iterate - through the ``tls_routes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListTlsRoutesResponse` - 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[tls_route.ListTlsRoutesResponse]], - request: tls_route.ListTlsRoutesRequest, - response: tls_route.ListTlsRoutesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListTlsRoutesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListTlsRoutesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tls_route.ListTlsRoutesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[tls_route.ListTlsRoutesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[tls_route.TlsRoute]: - async def async_generator(): - async for page in self.pages: - for response in page.tls_routes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceBindingsPager: - """A pager for iterating through ``list_service_bindings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``service_bindings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServiceBindings`` requests and continue to iterate - through the ``service_bindings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` - 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[..., service_binding.ListServiceBindingsResponse], - request: service_binding.ListServiceBindingsRequest, - response: service_binding.ListServiceBindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListServiceBindingsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListServiceBindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service_binding.ListServiceBindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service_binding.ListServiceBindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[service_binding.ServiceBinding]: - for page in self.pages: - yield from page.service_bindings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceBindingsAsyncPager: - """A pager for iterating through ``list_service_bindings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``service_bindings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServiceBindings`` requests and continue to iterate - through the ``service_bindings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListServiceBindingsResponse` - 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[service_binding.ListServiceBindingsResponse]], - request: service_binding.ListServiceBindingsRequest, - response: service_binding.ListServiceBindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListServiceBindingsRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListServiceBindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service_binding.ListServiceBindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service_binding.ListServiceBindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[service_binding.ServiceBinding]: - async def async_generator(): - async for page in self.pages: - for response in page.service_bindings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMeshesPager: - """A pager for iterating through ``list_meshes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListMeshesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``meshes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMeshes`` requests and continue to iterate - through the ``meshes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListMeshesResponse` - 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[..., mesh.ListMeshesResponse], - request: mesh.ListMeshesRequest, - response: mesh.ListMeshesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListMeshesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListMeshesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = mesh.ListMeshesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[mesh.ListMeshesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[mesh.Mesh]: - for page in self.pages: - yield from page.meshes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMeshesAsyncPager: - """A pager for iterating through ``list_meshes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_services_v1.types.ListMeshesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``meshes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMeshes`` requests and continue to iterate - through the ``meshes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_services_v1.types.ListMeshesResponse` - 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[mesh.ListMeshesResponse]], - request: mesh.ListMeshesRequest, - response: mesh.ListMeshesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_services_v1.types.ListMeshesRequest): - The initial request object. - response (google.cloud.network_services_v1.types.ListMeshesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = mesh.ListMeshesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[mesh.ListMeshesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[mesh.Mesh]: - async def async_generator(): - async for page in self.pages: - for response in page.meshes: - 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-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py deleted file mode 100644 index 44d166b35e75..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 NetworkServicesTransport -from .grpc import NetworkServicesGrpcTransport -from .grpc_asyncio import NetworkServicesGrpcAsyncIOTransport -from .rest import NetworkServicesRestTransport -from .rest import NetworkServicesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkServicesTransport]] -_transport_registry['grpc'] = NetworkServicesGrpcTransport -_transport_registry['grpc_asyncio'] = NetworkServicesGrpcAsyncIOTransport -_transport_registry['rest'] = NetworkServicesRestTransport - -__all__ = ( - 'NetworkServicesTransport', - 'NetworkServicesGrpcTransport', - 'NetworkServicesGrpcAsyncIOTransport', - 'NetworkServicesRestTransport', - 'NetworkServicesRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py deleted file mode 100644 index 21230f51ded9..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/base.py +++ /dev/null @@ -1,791 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_services_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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__) - - -class NetworkServicesTransport(abc.ABC): - """Abstract transport class for NetworkServices.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networkservices.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: 'networkservices.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 no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_endpoint_policies: gapic_v1.method.wrap_method( - self.list_endpoint_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_endpoint_policy: gapic_v1.method.wrap_method( - self.get_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_endpoint_policy: gapic_v1.method.wrap_method( - self.create_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_endpoint_policy: gapic_v1.method.wrap_method( - self.update_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_endpoint_policy: gapic_v1.method.wrap_method( - self.delete_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_gateways: gapic_v1.method.wrap_method( - self.list_gateways, - default_timeout=None, - client_info=client_info, - ), - self.get_gateway: gapic_v1.method.wrap_method( - self.get_gateway, - default_timeout=None, - client_info=client_info, - ), - self.create_gateway: gapic_v1.method.wrap_method( - self.create_gateway, - default_timeout=None, - client_info=client_info, - ), - self.update_gateway: gapic_v1.method.wrap_method( - self.update_gateway, - default_timeout=None, - client_info=client_info, - ), - self.delete_gateway: gapic_v1.method.wrap_method( - self.delete_gateway, - default_timeout=None, - client_info=client_info, - ), - self.list_grpc_routes: gapic_v1.method.wrap_method( - self.list_grpc_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_grpc_route: gapic_v1.method.wrap_method( - self.get_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.create_grpc_route: gapic_v1.method.wrap_method( - self.create_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.update_grpc_route: gapic_v1.method.wrap_method( - self.update_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_grpc_route: gapic_v1.method.wrap_method( - self.delete_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.list_http_routes: gapic_v1.method.wrap_method( - self.list_http_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_http_route: gapic_v1.method.wrap_method( - self.get_http_route, - default_timeout=None, - client_info=client_info, - ), - self.create_http_route: gapic_v1.method.wrap_method( - self.create_http_route, - default_timeout=None, - client_info=client_info, - ), - self.update_http_route: gapic_v1.method.wrap_method( - self.update_http_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_http_route: gapic_v1.method.wrap_method( - self.delete_http_route, - default_timeout=None, - client_info=client_info, - ), - self.list_tcp_routes: gapic_v1.method.wrap_method( - self.list_tcp_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_tcp_route: gapic_v1.method.wrap_method( - self.get_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.create_tcp_route: gapic_v1.method.wrap_method( - self.create_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.update_tcp_route: gapic_v1.method.wrap_method( - self.update_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_tcp_route: gapic_v1.method.wrap_method( - self.delete_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.list_tls_routes: gapic_v1.method.wrap_method( - self.list_tls_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_tls_route: gapic_v1.method.wrap_method( - self.get_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.create_tls_route: gapic_v1.method.wrap_method( - self.create_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.update_tls_route: gapic_v1.method.wrap_method( - self.update_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_tls_route: gapic_v1.method.wrap_method( - self.delete_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.list_service_bindings: gapic_v1.method.wrap_method( - self.list_service_bindings, - default_timeout=None, - client_info=client_info, - ), - self.get_service_binding: gapic_v1.method.wrap_method( - self.get_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.create_service_binding: gapic_v1.method.wrap_method( - self.create_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.delete_service_binding: gapic_v1.method.wrap_method( - self.delete_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.list_meshes: gapic_v1.method.wrap_method( - self.list_meshes, - default_timeout=None, - client_info=client_info, - ), - self.get_mesh: gapic_v1.method.wrap_method( - self.get_mesh, - default_timeout=None, - client_info=client_info, - ), - self.create_mesh: gapic_v1.method.wrap_method( - self.create_mesh, - default_timeout=None, - client_info=client_info, - ), - self.update_mesh: gapic_v1.method.wrap_method( - self.update_mesh, - default_timeout=None, - client_info=client_info, - ), - self.delete_mesh: gapic_v1.method.wrap_method( - self.delete_mesh, - 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_endpoint_policies(self) -> Callable[ - [endpoint_policy.ListEndpointPoliciesRequest], - Union[ - endpoint_policy.ListEndpointPoliciesResponse, - Awaitable[endpoint_policy.ListEndpointPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_endpoint_policy(self) -> Callable[ - [endpoint_policy.GetEndpointPolicyRequest], - Union[ - endpoint_policy.EndpointPolicy, - Awaitable[endpoint_policy.EndpointPolicy] - ]]: - raise NotImplementedError() - - @property - def create_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.CreateEndpointPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.UpdateEndpointPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_endpoint_policy(self) -> Callable[ - [endpoint_policy.DeleteEndpointPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_gateways(self) -> Callable[ - [gateway.ListGatewaysRequest], - Union[ - gateway.ListGatewaysResponse, - Awaitable[gateway.ListGatewaysResponse] - ]]: - raise NotImplementedError() - - @property - def get_gateway(self) -> Callable[ - [gateway.GetGatewayRequest], - Union[ - gateway.Gateway, - Awaitable[gateway.Gateway] - ]]: - raise NotImplementedError() - - @property - def create_gateway(self) -> Callable[ - [gcn_gateway.CreateGatewayRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_gateway(self) -> Callable[ - [gcn_gateway.UpdateGatewayRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_gateway(self) -> Callable[ - [gateway.DeleteGatewayRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_grpc_routes(self) -> Callable[ - [grpc_route.ListGrpcRoutesRequest], - Union[ - grpc_route.ListGrpcRoutesResponse, - Awaitable[grpc_route.ListGrpcRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def get_grpc_route(self) -> Callable[ - [grpc_route.GetGrpcRouteRequest], - Union[ - grpc_route.GrpcRoute, - Awaitable[grpc_route.GrpcRoute] - ]]: - raise NotImplementedError() - - @property - def create_grpc_route(self) -> Callable[ - [gcn_grpc_route.CreateGrpcRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_grpc_route(self) -> Callable[ - [gcn_grpc_route.UpdateGrpcRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_grpc_route(self) -> Callable[ - [grpc_route.DeleteGrpcRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_http_routes(self) -> Callable[ - [http_route.ListHttpRoutesRequest], - Union[ - http_route.ListHttpRoutesResponse, - Awaitable[http_route.ListHttpRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def get_http_route(self) -> Callable[ - [http_route.GetHttpRouteRequest], - Union[ - http_route.HttpRoute, - Awaitable[http_route.HttpRoute] - ]]: - raise NotImplementedError() - - @property - def create_http_route(self) -> Callable[ - [gcn_http_route.CreateHttpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_http_route(self) -> Callable[ - [gcn_http_route.UpdateHttpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_http_route(self) -> Callable[ - [http_route.DeleteHttpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_tcp_routes(self) -> Callable[ - [tcp_route.ListTcpRoutesRequest], - Union[ - tcp_route.ListTcpRoutesResponse, - Awaitable[tcp_route.ListTcpRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def get_tcp_route(self) -> Callable[ - [tcp_route.GetTcpRouteRequest], - Union[ - tcp_route.TcpRoute, - Awaitable[tcp_route.TcpRoute] - ]]: - raise NotImplementedError() - - @property - def create_tcp_route(self) -> Callable[ - [gcn_tcp_route.CreateTcpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_tcp_route(self) -> Callable[ - [gcn_tcp_route.UpdateTcpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_tcp_route(self) -> Callable[ - [tcp_route.DeleteTcpRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_tls_routes(self) -> Callable[ - [tls_route.ListTlsRoutesRequest], - Union[ - tls_route.ListTlsRoutesResponse, - Awaitable[tls_route.ListTlsRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def get_tls_route(self) -> Callable[ - [tls_route.GetTlsRouteRequest], - Union[ - tls_route.TlsRoute, - Awaitable[tls_route.TlsRoute] - ]]: - raise NotImplementedError() - - @property - def create_tls_route(self) -> Callable[ - [gcn_tls_route.CreateTlsRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_tls_route(self) -> Callable[ - [gcn_tls_route.UpdateTlsRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_tls_route(self) -> Callable[ - [tls_route.DeleteTlsRouteRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_service_bindings(self) -> Callable[ - [service_binding.ListServiceBindingsRequest], - Union[ - service_binding.ListServiceBindingsResponse, - Awaitable[service_binding.ListServiceBindingsResponse] - ]]: - raise NotImplementedError() - - @property - def get_service_binding(self) -> Callable[ - [service_binding.GetServiceBindingRequest], - Union[ - service_binding.ServiceBinding, - Awaitable[service_binding.ServiceBinding] - ]]: - raise NotImplementedError() - - @property - def create_service_binding(self) -> Callable[ - [gcn_service_binding.CreateServiceBindingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_service_binding(self) -> Callable[ - [service_binding.DeleteServiceBindingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_meshes(self) -> Callable[ - [mesh.ListMeshesRequest], - Union[ - mesh.ListMeshesResponse, - Awaitable[mesh.ListMeshesResponse] - ]]: - raise NotImplementedError() - - @property - def get_mesh(self) -> Callable[ - [mesh.GetMeshRequest], - Union[ - mesh.Mesh, - Awaitable[mesh.Mesh] - ]]: - raise NotImplementedError() - - @property - def create_mesh(self) -> Callable[ - [gcn_mesh.CreateMeshRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_mesh(self) -> Callable[ - [gcn_mesh.UpdateMeshRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_mesh(self) -> Callable[ - [mesh.DeleteMeshRequest], - 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__ = ( - 'NetworkServicesTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py deleted file mode 100644 index 4065be859d2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc.py +++ /dev/null @@ -1,1487 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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 NetworkServicesTransport, DEFAULT_CLIENT_INFO - - -class NetworkServicesGrpcTransport(NetworkServicesTransport): - """gRPC backend transport for NetworkServices. - - 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 = 'networkservices.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: 'networkservices.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 = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'networkservices.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_endpoint_policies(self) -> Callable[ - [endpoint_policy.ListEndpointPoliciesRequest], - endpoint_policy.ListEndpointPoliciesResponse]: - r"""Return a callable for the list endpoint policies method over gRPC. - - Lists EndpointPolicies in a given project and - location. - - Returns: - Callable[[~.ListEndpointPoliciesRequest], - ~.ListEndpointPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint_policies' not in self._stubs: - self._stubs['list_endpoint_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListEndpointPolicies', - request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, - response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, - ) - return self._stubs['list_endpoint_policies'] - - @property - def get_endpoint_policy(self) -> Callable[ - [endpoint_policy.GetEndpointPolicyRequest], - endpoint_policy.EndpointPolicy]: - r"""Return a callable for the get endpoint policy method over gRPC. - - Gets details of a single EndpointPolicy. - - Returns: - Callable[[~.GetEndpointPolicyRequest], - ~.EndpointPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint_policy' not in self._stubs: - self._stubs['get_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetEndpointPolicy', - request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, - response_deserializer=endpoint_policy.EndpointPolicy.deserialize, - ) - return self._stubs['get_endpoint_policy'] - - @property - def create_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.CreateEndpointPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create endpoint policy method over gRPC. - - Creates a new EndpointPolicy in a given project and - location. - - Returns: - Callable[[~.CreateEndpointPolicyRequest], - ~.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_endpoint_policy' not in self._stubs: - self._stubs['create_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateEndpointPolicy', - request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_endpoint_policy'] - - @property - def update_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.UpdateEndpointPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update endpoint policy method over gRPC. - - Updates the parameters of a single EndpointPolicy. - - Returns: - Callable[[~.UpdateEndpointPolicyRequest], - ~.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_endpoint_policy' not in self._stubs: - self._stubs['update_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateEndpointPolicy', - request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_endpoint_policy'] - - @property - def delete_endpoint_policy(self) -> Callable[ - [endpoint_policy.DeleteEndpointPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete endpoint policy method over gRPC. - - Deletes a single EndpointPolicy. - - Returns: - Callable[[~.DeleteEndpointPolicyRequest], - ~.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_endpoint_policy' not in self._stubs: - self._stubs['delete_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteEndpointPolicy', - request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_endpoint_policy'] - - @property - def list_gateways(self) -> Callable[ - [gateway.ListGatewaysRequest], - gateway.ListGatewaysResponse]: - r"""Return a callable for the list gateways method over gRPC. - - Lists Gateways in a given project and location. - - Returns: - Callable[[~.ListGatewaysRequest], - ~.ListGatewaysResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_gateways' not in self._stubs: - self._stubs['list_gateways'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListGateways', - request_serializer=gateway.ListGatewaysRequest.serialize, - response_deserializer=gateway.ListGatewaysResponse.deserialize, - ) - return self._stubs['list_gateways'] - - @property - def get_gateway(self) -> Callable[ - [gateway.GetGatewayRequest], - gateway.Gateway]: - r"""Return a callable for the get gateway method over gRPC. - - Gets details of a single Gateway. - - Returns: - Callable[[~.GetGatewayRequest], - ~.Gateway]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_gateway' not in self._stubs: - self._stubs['get_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetGateway', - request_serializer=gateway.GetGatewayRequest.serialize, - response_deserializer=gateway.Gateway.deserialize, - ) - return self._stubs['get_gateway'] - - @property - def create_gateway(self) -> Callable[ - [gcn_gateway.CreateGatewayRequest], - operations_pb2.Operation]: - r"""Return a callable for the create gateway method over gRPC. - - Creates a new Gateway in a given project and - location. - - Returns: - Callable[[~.CreateGatewayRequest], - ~.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_gateway' not in self._stubs: - self._stubs['create_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateGateway', - request_serializer=gcn_gateway.CreateGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_gateway'] - - @property - def update_gateway(self) -> Callable[ - [gcn_gateway.UpdateGatewayRequest], - operations_pb2.Operation]: - r"""Return a callable for the update gateway method over gRPC. - - Updates the parameters of a single Gateway. - - Returns: - Callable[[~.UpdateGatewayRequest], - ~.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_gateway' not in self._stubs: - self._stubs['update_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateGateway', - request_serializer=gcn_gateway.UpdateGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_gateway'] - - @property - def delete_gateway(self) -> Callable[ - [gateway.DeleteGatewayRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete gateway method over gRPC. - - Deletes a single Gateway. - - Returns: - Callable[[~.DeleteGatewayRequest], - ~.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_gateway' not in self._stubs: - self._stubs['delete_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteGateway', - request_serializer=gateway.DeleteGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_gateway'] - - @property - def list_grpc_routes(self) -> Callable[ - [grpc_route.ListGrpcRoutesRequest], - grpc_route.ListGrpcRoutesResponse]: - r"""Return a callable for the list grpc routes method over gRPC. - - Lists GrpcRoutes in a given project and location. - - Returns: - Callable[[~.ListGrpcRoutesRequest], - ~.ListGrpcRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_grpc_routes' not in self._stubs: - self._stubs['list_grpc_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListGrpcRoutes', - request_serializer=grpc_route.ListGrpcRoutesRequest.serialize, - response_deserializer=grpc_route.ListGrpcRoutesResponse.deserialize, - ) - return self._stubs['list_grpc_routes'] - - @property - def get_grpc_route(self) -> Callable[ - [grpc_route.GetGrpcRouteRequest], - grpc_route.GrpcRoute]: - r"""Return a callable for the get grpc route method over gRPC. - - Gets details of a single GrpcRoute. - - Returns: - Callable[[~.GetGrpcRouteRequest], - ~.GrpcRoute]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_grpc_route' not in self._stubs: - self._stubs['get_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetGrpcRoute', - request_serializer=grpc_route.GetGrpcRouteRequest.serialize, - response_deserializer=grpc_route.GrpcRoute.deserialize, - ) - return self._stubs['get_grpc_route'] - - @property - def create_grpc_route(self) -> Callable[ - [gcn_grpc_route.CreateGrpcRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the create grpc route method over gRPC. - - Creates a new GrpcRoute in a given project and - location. - - Returns: - Callable[[~.CreateGrpcRouteRequest], - ~.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_grpc_route' not in self._stubs: - self._stubs['create_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateGrpcRoute', - request_serializer=gcn_grpc_route.CreateGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_grpc_route'] - - @property - def update_grpc_route(self) -> Callable[ - [gcn_grpc_route.UpdateGrpcRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the update grpc route method over gRPC. - - Updates the parameters of a single GrpcRoute. - - Returns: - Callable[[~.UpdateGrpcRouteRequest], - ~.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_grpc_route' not in self._stubs: - self._stubs['update_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateGrpcRoute', - request_serializer=gcn_grpc_route.UpdateGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_grpc_route'] - - @property - def delete_grpc_route(self) -> Callable[ - [grpc_route.DeleteGrpcRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete grpc route method over gRPC. - - Deletes a single GrpcRoute. - - Returns: - Callable[[~.DeleteGrpcRouteRequest], - ~.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_grpc_route' not in self._stubs: - self._stubs['delete_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteGrpcRoute', - request_serializer=grpc_route.DeleteGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_grpc_route'] - - @property - def list_http_routes(self) -> Callable[ - [http_route.ListHttpRoutesRequest], - http_route.ListHttpRoutesResponse]: - r"""Return a callable for the list http routes method over gRPC. - - Lists HttpRoute in a given project and location. - - Returns: - Callable[[~.ListHttpRoutesRequest], - ~.ListHttpRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_http_routes' not in self._stubs: - self._stubs['list_http_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListHttpRoutes', - request_serializer=http_route.ListHttpRoutesRequest.serialize, - response_deserializer=http_route.ListHttpRoutesResponse.deserialize, - ) - return self._stubs['list_http_routes'] - - @property - def get_http_route(self) -> Callable[ - [http_route.GetHttpRouteRequest], - http_route.HttpRoute]: - r"""Return a callable for the get http route method over gRPC. - - Gets details of a single HttpRoute. - - Returns: - Callable[[~.GetHttpRouteRequest], - ~.HttpRoute]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_http_route' not in self._stubs: - self._stubs['get_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetHttpRoute', - request_serializer=http_route.GetHttpRouteRequest.serialize, - response_deserializer=http_route.HttpRoute.deserialize, - ) - return self._stubs['get_http_route'] - - @property - def create_http_route(self) -> Callable[ - [gcn_http_route.CreateHttpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the create http route method over gRPC. - - Creates a new HttpRoute in a given project and - location. - - Returns: - Callable[[~.CreateHttpRouteRequest], - ~.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_http_route' not in self._stubs: - self._stubs['create_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateHttpRoute', - request_serializer=gcn_http_route.CreateHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_http_route'] - - @property - def update_http_route(self) -> Callable[ - [gcn_http_route.UpdateHttpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the update http route method over gRPC. - - Updates the parameters of a single HttpRoute. - - Returns: - Callable[[~.UpdateHttpRouteRequest], - ~.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_http_route' not in self._stubs: - self._stubs['update_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateHttpRoute', - request_serializer=gcn_http_route.UpdateHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_http_route'] - - @property - def delete_http_route(self) -> Callable[ - [http_route.DeleteHttpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete http route method over gRPC. - - Deletes a single HttpRoute. - - Returns: - Callable[[~.DeleteHttpRouteRequest], - ~.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_http_route' not in self._stubs: - self._stubs['delete_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteHttpRoute', - request_serializer=http_route.DeleteHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_http_route'] - - @property - def list_tcp_routes(self) -> Callable[ - [tcp_route.ListTcpRoutesRequest], - tcp_route.ListTcpRoutesResponse]: - r"""Return a callable for the list tcp routes method over gRPC. - - Lists TcpRoute in a given project and location. - - Returns: - Callable[[~.ListTcpRoutesRequest], - ~.ListTcpRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tcp_routes' not in self._stubs: - self._stubs['list_tcp_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListTcpRoutes', - request_serializer=tcp_route.ListTcpRoutesRequest.serialize, - response_deserializer=tcp_route.ListTcpRoutesResponse.deserialize, - ) - return self._stubs['list_tcp_routes'] - - @property - def get_tcp_route(self) -> Callable[ - [tcp_route.GetTcpRouteRequest], - tcp_route.TcpRoute]: - r"""Return a callable for the get tcp route method over gRPC. - - Gets details of a single TcpRoute. - - Returns: - Callable[[~.GetTcpRouteRequest], - ~.TcpRoute]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tcp_route' not in self._stubs: - self._stubs['get_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetTcpRoute', - request_serializer=tcp_route.GetTcpRouteRequest.serialize, - response_deserializer=tcp_route.TcpRoute.deserialize, - ) - return self._stubs['get_tcp_route'] - - @property - def create_tcp_route(self) -> Callable[ - [gcn_tcp_route.CreateTcpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the create tcp route method over gRPC. - - Creates a new TcpRoute in a given project and - location. - - Returns: - Callable[[~.CreateTcpRouteRequest], - ~.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_tcp_route' not in self._stubs: - self._stubs['create_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateTcpRoute', - request_serializer=gcn_tcp_route.CreateTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tcp_route'] - - @property - def update_tcp_route(self) -> Callable[ - [gcn_tcp_route.UpdateTcpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the update tcp route method over gRPC. - - Updates the parameters of a single TcpRoute. - - Returns: - Callable[[~.UpdateTcpRouteRequest], - ~.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_tcp_route' not in self._stubs: - self._stubs['update_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateTcpRoute', - request_serializer=gcn_tcp_route.UpdateTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tcp_route'] - - @property - def delete_tcp_route(self) -> Callable[ - [tcp_route.DeleteTcpRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete tcp route method over gRPC. - - Deletes a single TcpRoute. - - Returns: - Callable[[~.DeleteTcpRouteRequest], - ~.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_tcp_route' not in self._stubs: - self._stubs['delete_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteTcpRoute', - request_serializer=tcp_route.DeleteTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tcp_route'] - - @property - def list_tls_routes(self) -> Callable[ - [tls_route.ListTlsRoutesRequest], - tls_route.ListTlsRoutesResponse]: - r"""Return a callable for the list tls routes method over gRPC. - - Lists TlsRoute in a given project and location. - - Returns: - Callable[[~.ListTlsRoutesRequest], - ~.ListTlsRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tls_routes' not in self._stubs: - self._stubs['list_tls_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListTlsRoutes', - request_serializer=tls_route.ListTlsRoutesRequest.serialize, - response_deserializer=tls_route.ListTlsRoutesResponse.deserialize, - ) - return self._stubs['list_tls_routes'] - - @property - def get_tls_route(self) -> Callable[ - [tls_route.GetTlsRouteRequest], - tls_route.TlsRoute]: - r"""Return a callable for the get tls route method over gRPC. - - Gets details of a single TlsRoute. - - Returns: - Callable[[~.GetTlsRouteRequest], - ~.TlsRoute]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tls_route' not in self._stubs: - self._stubs['get_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetTlsRoute', - request_serializer=tls_route.GetTlsRouteRequest.serialize, - response_deserializer=tls_route.TlsRoute.deserialize, - ) - return self._stubs['get_tls_route'] - - @property - def create_tls_route(self) -> Callable[ - [gcn_tls_route.CreateTlsRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the create tls route method over gRPC. - - Creates a new TlsRoute in a given project and - location. - - Returns: - Callable[[~.CreateTlsRouteRequest], - ~.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_tls_route' not in self._stubs: - self._stubs['create_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateTlsRoute', - request_serializer=gcn_tls_route.CreateTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tls_route'] - - @property - def update_tls_route(self) -> Callable[ - [gcn_tls_route.UpdateTlsRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the update tls route method over gRPC. - - Updates the parameters of a single TlsRoute. - - Returns: - Callable[[~.UpdateTlsRouteRequest], - ~.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_tls_route' not in self._stubs: - self._stubs['update_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateTlsRoute', - request_serializer=gcn_tls_route.UpdateTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tls_route'] - - @property - def delete_tls_route(self) -> Callable[ - [tls_route.DeleteTlsRouteRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete tls route method over gRPC. - - Deletes a single TlsRoute. - - Returns: - Callable[[~.DeleteTlsRouteRequest], - ~.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_tls_route' not in self._stubs: - self._stubs['delete_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteTlsRoute', - request_serializer=tls_route.DeleteTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tls_route'] - - @property - def list_service_bindings(self) -> Callable[ - [service_binding.ListServiceBindingsRequest], - service_binding.ListServiceBindingsResponse]: - r"""Return a callable for the list service bindings method over gRPC. - - Lists ServiceBinding in a given project and location. - - Returns: - Callable[[~.ListServiceBindingsRequest], - ~.ListServiceBindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_bindings' not in self._stubs: - self._stubs['list_service_bindings'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListServiceBindings', - request_serializer=service_binding.ListServiceBindingsRequest.serialize, - response_deserializer=service_binding.ListServiceBindingsResponse.deserialize, - ) - return self._stubs['list_service_bindings'] - - @property - def get_service_binding(self) -> Callable[ - [service_binding.GetServiceBindingRequest], - service_binding.ServiceBinding]: - r"""Return a callable for the get service binding method over gRPC. - - Gets details of a single ServiceBinding. - - Returns: - Callable[[~.GetServiceBindingRequest], - ~.ServiceBinding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_binding' not in self._stubs: - self._stubs['get_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetServiceBinding', - request_serializer=service_binding.GetServiceBindingRequest.serialize, - response_deserializer=service_binding.ServiceBinding.deserialize, - ) - return self._stubs['get_service_binding'] - - @property - def create_service_binding(self) -> Callable[ - [gcn_service_binding.CreateServiceBindingRequest], - operations_pb2.Operation]: - r"""Return a callable for the create service binding method over gRPC. - - Creates a new ServiceBinding in a given project and - location. - - Returns: - Callable[[~.CreateServiceBindingRequest], - ~.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_service_binding' not in self._stubs: - self._stubs['create_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateServiceBinding', - request_serializer=gcn_service_binding.CreateServiceBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service_binding'] - - @property - def delete_service_binding(self) -> Callable[ - [service_binding.DeleteServiceBindingRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete service binding method over gRPC. - - Deletes a single ServiceBinding. - - Returns: - Callable[[~.DeleteServiceBindingRequest], - ~.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_service_binding' not in self._stubs: - self._stubs['delete_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteServiceBinding', - request_serializer=service_binding.DeleteServiceBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service_binding'] - - @property - def list_meshes(self) -> Callable[ - [mesh.ListMeshesRequest], - mesh.ListMeshesResponse]: - r"""Return a callable for the list meshes method over gRPC. - - Lists Meshes in a given project and location. - - Returns: - Callable[[~.ListMeshesRequest], - ~.ListMeshesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_meshes' not in self._stubs: - self._stubs['list_meshes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListMeshes', - request_serializer=mesh.ListMeshesRequest.serialize, - response_deserializer=mesh.ListMeshesResponse.deserialize, - ) - return self._stubs['list_meshes'] - - @property - def get_mesh(self) -> Callable[ - [mesh.GetMeshRequest], - mesh.Mesh]: - r"""Return a callable for the get mesh method over gRPC. - - Gets details of a single Mesh. - - Returns: - Callable[[~.GetMeshRequest], - ~.Mesh]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mesh' not in self._stubs: - self._stubs['get_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetMesh', - request_serializer=mesh.GetMeshRequest.serialize, - response_deserializer=mesh.Mesh.deserialize, - ) - return self._stubs['get_mesh'] - - @property - def create_mesh(self) -> Callable[ - [gcn_mesh.CreateMeshRequest], - operations_pb2.Operation]: - r"""Return a callable for the create mesh method over gRPC. - - Creates a new Mesh in a given project and location. - - Returns: - Callable[[~.CreateMeshRequest], - ~.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_mesh' not in self._stubs: - self._stubs['create_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateMesh', - request_serializer=gcn_mesh.CreateMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_mesh'] - - @property - def update_mesh(self) -> Callable[ - [gcn_mesh.UpdateMeshRequest], - operations_pb2.Operation]: - r"""Return a callable for the update mesh method over gRPC. - - Updates the parameters of a single Mesh. - - Returns: - Callable[[~.UpdateMeshRequest], - ~.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_mesh' not in self._stubs: - self._stubs['update_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateMesh', - request_serializer=gcn_mesh.UpdateMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_mesh'] - - @property - def delete_mesh(self) -> Callable[ - [mesh.DeleteMeshRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete mesh method over gRPC. - - Deletes a single Mesh. - - Returns: - Callable[[~.DeleteMeshRequest], - ~.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_mesh' not in self._stubs: - self._stubs['delete_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteMesh', - request_serializer=mesh.DeleteMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_mesh'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'NetworkServicesGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py deleted file mode 100644 index f4edc43e75ea..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/grpc_asyncio.py +++ /dev/null @@ -1,1687 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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 NetworkServicesTransport, DEFAULT_CLIENT_INFO -from .grpc import NetworkServicesGrpcTransport - - -class NetworkServicesGrpcAsyncIOTransport(NetworkServicesTransport): - """gRPC AsyncIO backend transport for NetworkServices. - - 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 = 'networkservices.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 = 'networkservices.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: 'networkservices.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 = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_endpoint_policies(self) -> Callable[ - [endpoint_policy.ListEndpointPoliciesRequest], - Awaitable[endpoint_policy.ListEndpointPoliciesResponse]]: - r"""Return a callable for the list endpoint policies method over gRPC. - - Lists EndpointPolicies in a given project and - location. - - Returns: - Callable[[~.ListEndpointPoliciesRequest], - Awaitable[~.ListEndpointPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint_policies' not in self._stubs: - self._stubs['list_endpoint_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListEndpointPolicies', - request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, - response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, - ) - return self._stubs['list_endpoint_policies'] - - @property - def get_endpoint_policy(self) -> Callable[ - [endpoint_policy.GetEndpointPolicyRequest], - Awaitable[endpoint_policy.EndpointPolicy]]: - r"""Return a callable for the get endpoint policy method over gRPC. - - Gets details of a single EndpointPolicy. - - Returns: - Callable[[~.GetEndpointPolicyRequest], - Awaitable[~.EndpointPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_endpoint_policy' not in self._stubs: - self._stubs['get_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetEndpointPolicy', - request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, - response_deserializer=endpoint_policy.EndpointPolicy.deserialize, - ) - return self._stubs['get_endpoint_policy'] - - @property - def create_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.CreateEndpointPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create endpoint policy method over gRPC. - - Creates a new EndpointPolicy in a given project and - location. - - Returns: - Callable[[~.CreateEndpointPolicyRequest], - 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_endpoint_policy' not in self._stubs: - self._stubs['create_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateEndpointPolicy', - request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_endpoint_policy'] - - @property - def update_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.UpdateEndpointPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update endpoint policy method over gRPC. - - Updates the parameters of a single EndpointPolicy. - - Returns: - Callable[[~.UpdateEndpointPolicyRequest], - 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_endpoint_policy' not in self._stubs: - self._stubs['update_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateEndpointPolicy', - request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_endpoint_policy'] - - @property - def delete_endpoint_policy(self) -> Callable[ - [endpoint_policy.DeleteEndpointPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete endpoint policy method over gRPC. - - Deletes a single EndpointPolicy. - - Returns: - Callable[[~.DeleteEndpointPolicyRequest], - 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_endpoint_policy' not in self._stubs: - self._stubs['delete_endpoint_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteEndpointPolicy', - request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_endpoint_policy'] - - @property - def list_gateways(self) -> Callable[ - [gateway.ListGatewaysRequest], - Awaitable[gateway.ListGatewaysResponse]]: - r"""Return a callable for the list gateways method over gRPC. - - Lists Gateways in a given project and location. - - Returns: - Callable[[~.ListGatewaysRequest], - Awaitable[~.ListGatewaysResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_gateways' not in self._stubs: - self._stubs['list_gateways'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListGateways', - request_serializer=gateway.ListGatewaysRequest.serialize, - response_deserializer=gateway.ListGatewaysResponse.deserialize, - ) - return self._stubs['list_gateways'] - - @property - def get_gateway(self) -> Callable[ - [gateway.GetGatewayRequest], - Awaitable[gateway.Gateway]]: - r"""Return a callable for the get gateway method over gRPC. - - Gets details of a single Gateway. - - Returns: - Callable[[~.GetGatewayRequest], - Awaitable[~.Gateway]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_gateway' not in self._stubs: - self._stubs['get_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetGateway', - request_serializer=gateway.GetGatewayRequest.serialize, - response_deserializer=gateway.Gateway.deserialize, - ) - return self._stubs['get_gateway'] - - @property - def create_gateway(self) -> Callable[ - [gcn_gateway.CreateGatewayRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create gateway method over gRPC. - - Creates a new Gateway in a given project and - location. - - Returns: - Callable[[~.CreateGatewayRequest], - 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_gateway' not in self._stubs: - self._stubs['create_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateGateway', - request_serializer=gcn_gateway.CreateGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_gateway'] - - @property - def update_gateway(self) -> Callable[ - [gcn_gateway.UpdateGatewayRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update gateway method over gRPC. - - Updates the parameters of a single Gateway. - - Returns: - Callable[[~.UpdateGatewayRequest], - 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_gateway' not in self._stubs: - self._stubs['update_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateGateway', - request_serializer=gcn_gateway.UpdateGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_gateway'] - - @property - def delete_gateway(self) -> Callable[ - [gateway.DeleteGatewayRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete gateway method over gRPC. - - Deletes a single Gateway. - - Returns: - Callable[[~.DeleteGatewayRequest], - 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_gateway' not in self._stubs: - self._stubs['delete_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteGateway', - request_serializer=gateway.DeleteGatewayRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_gateway'] - - @property - def list_grpc_routes(self) -> Callable[ - [grpc_route.ListGrpcRoutesRequest], - Awaitable[grpc_route.ListGrpcRoutesResponse]]: - r"""Return a callable for the list grpc routes method over gRPC. - - Lists GrpcRoutes in a given project and location. - - Returns: - Callable[[~.ListGrpcRoutesRequest], - Awaitable[~.ListGrpcRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_grpc_routes' not in self._stubs: - self._stubs['list_grpc_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListGrpcRoutes', - request_serializer=grpc_route.ListGrpcRoutesRequest.serialize, - response_deserializer=grpc_route.ListGrpcRoutesResponse.deserialize, - ) - return self._stubs['list_grpc_routes'] - - @property - def get_grpc_route(self) -> Callable[ - [grpc_route.GetGrpcRouteRequest], - Awaitable[grpc_route.GrpcRoute]]: - r"""Return a callable for the get grpc route method over gRPC. - - Gets details of a single GrpcRoute. - - Returns: - Callable[[~.GetGrpcRouteRequest], - Awaitable[~.GrpcRoute]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_grpc_route' not in self._stubs: - self._stubs['get_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetGrpcRoute', - request_serializer=grpc_route.GetGrpcRouteRequest.serialize, - response_deserializer=grpc_route.GrpcRoute.deserialize, - ) - return self._stubs['get_grpc_route'] - - @property - def create_grpc_route(self) -> Callable[ - [gcn_grpc_route.CreateGrpcRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create grpc route method over gRPC. - - Creates a new GrpcRoute in a given project and - location. - - Returns: - Callable[[~.CreateGrpcRouteRequest], - 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_grpc_route' not in self._stubs: - self._stubs['create_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateGrpcRoute', - request_serializer=gcn_grpc_route.CreateGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_grpc_route'] - - @property - def update_grpc_route(self) -> Callable[ - [gcn_grpc_route.UpdateGrpcRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update grpc route method over gRPC. - - Updates the parameters of a single GrpcRoute. - - Returns: - Callable[[~.UpdateGrpcRouteRequest], - 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_grpc_route' not in self._stubs: - self._stubs['update_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateGrpcRoute', - request_serializer=gcn_grpc_route.UpdateGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_grpc_route'] - - @property - def delete_grpc_route(self) -> Callable[ - [grpc_route.DeleteGrpcRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete grpc route method over gRPC. - - Deletes a single GrpcRoute. - - Returns: - Callable[[~.DeleteGrpcRouteRequest], - 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_grpc_route' not in self._stubs: - self._stubs['delete_grpc_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteGrpcRoute', - request_serializer=grpc_route.DeleteGrpcRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_grpc_route'] - - @property - def list_http_routes(self) -> Callable[ - [http_route.ListHttpRoutesRequest], - Awaitable[http_route.ListHttpRoutesResponse]]: - r"""Return a callable for the list http routes method over gRPC. - - Lists HttpRoute in a given project and location. - - Returns: - Callable[[~.ListHttpRoutesRequest], - Awaitable[~.ListHttpRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_http_routes' not in self._stubs: - self._stubs['list_http_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListHttpRoutes', - request_serializer=http_route.ListHttpRoutesRequest.serialize, - response_deserializer=http_route.ListHttpRoutesResponse.deserialize, - ) - return self._stubs['list_http_routes'] - - @property - def get_http_route(self) -> Callable[ - [http_route.GetHttpRouteRequest], - Awaitable[http_route.HttpRoute]]: - r"""Return a callable for the get http route method over gRPC. - - Gets details of a single HttpRoute. - - Returns: - Callable[[~.GetHttpRouteRequest], - Awaitable[~.HttpRoute]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_http_route' not in self._stubs: - self._stubs['get_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetHttpRoute', - request_serializer=http_route.GetHttpRouteRequest.serialize, - response_deserializer=http_route.HttpRoute.deserialize, - ) - return self._stubs['get_http_route'] - - @property - def create_http_route(self) -> Callable[ - [gcn_http_route.CreateHttpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create http route method over gRPC. - - Creates a new HttpRoute in a given project and - location. - - Returns: - Callable[[~.CreateHttpRouteRequest], - 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_http_route' not in self._stubs: - self._stubs['create_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateHttpRoute', - request_serializer=gcn_http_route.CreateHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_http_route'] - - @property - def update_http_route(self) -> Callable[ - [gcn_http_route.UpdateHttpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update http route method over gRPC. - - Updates the parameters of a single HttpRoute. - - Returns: - Callable[[~.UpdateHttpRouteRequest], - 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_http_route' not in self._stubs: - self._stubs['update_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateHttpRoute', - request_serializer=gcn_http_route.UpdateHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_http_route'] - - @property - def delete_http_route(self) -> Callable[ - [http_route.DeleteHttpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete http route method over gRPC. - - Deletes a single HttpRoute. - - Returns: - Callable[[~.DeleteHttpRouteRequest], - 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_http_route' not in self._stubs: - self._stubs['delete_http_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteHttpRoute', - request_serializer=http_route.DeleteHttpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_http_route'] - - @property - def list_tcp_routes(self) -> Callable[ - [tcp_route.ListTcpRoutesRequest], - Awaitable[tcp_route.ListTcpRoutesResponse]]: - r"""Return a callable for the list tcp routes method over gRPC. - - Lists TcpRoute in a given project and location. - - Returns: - Callable[[~.ListTcpRoutesRequest], - Awaitable[~.ListTcpRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tcp_routes' not in self._stubs: - self._stubs['list_tcp_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListTcpRoutes', - request_serializer=tcp_route.ListTcpRoutesRequest.serialize, - response_deserializer=tcp_route.ListTcpRoutesResponse.deserialize, - ) - return self._stubs['list_tcp_routes'] - - @property - def get_tcp_route(self) -> Callable[ - [tcp_route.GetTcpRouteRequest], - Awaitable[tcp_route.TcpRoute]]: - r"""Return a callable for the get tcp route method over gRPC. - - Gets details of a single TcpRoute. - - Returns: - Callable[[~.GetTcpRouteRequest], - Awaitable[~.TcpRoute]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tcp_route' not in self._stubs: - self._stubs['get_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetTcpRoute', - request_serializer=tcp_route.GetTcpRouteRequest.serialize, - response_deserializer=tcp_route.TcpRoute.deserialize, - ) - return self._stubs['get_tcp_route'] - - @property - def create_tcp_route(self) -> Callable[ - [gcn_tcp_route.CreateTcpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create tcp route method over gRPC. - - Creates a new TcpRoute in a given project and - location. - - Returns: - Callable[[~.CreateTcpRouteRequest], - 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_tcp_route' not in self._stubs: - self._stubs['create_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateTcpRoute', - request_serializer=gcn_tcp_route.CreateTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tcp_route'] - - @property - def update_tcp_route(self) -> Callable[ - [gcn_tcp_route.UpdateTcpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update tcp route method over gRPC. - - Updates the parameters of a single TcpRoute. - - Returns: - Callable[[~.UpdateTcpRouteRequest], - 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_tcp_route' not in self._stubs: - self._stubs['update_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateTcpRoute', - request_serializer=gcn_tcp_route.UpdateTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tcp_route'] - - @property - def delete_tcp_route(self) -> Callable[ - [tcp_route.DeleteTcpRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete tcp route method over gRPC. - - Deletes a single TcpRoute. - - Returns: - Callable[[~.DeleteTcpRouteRequest], - 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_tcp_route' not in self._stubs: - self._stubs['delete_tcp_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteTcpRoute', - request_serializer=tcp_route.DeleteTcpRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tcp_route'] - - @property - def list_tls_routes(self) -> Callable[ - [tls_route.ListTlsRoutesRequest], - Awaitable[tls_route.ListTlsRoutesResponse]]: - r"""Return a callable for the list tls routes method over gRPC. - - Lists TlsRoute in a given project and location. - - Returns: - Callable[[~.ListTlsRoutesRequest], - Awaitable[~.ListTlsRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tls_routes' not in self._stubs: - self._stubs['list_tls_routes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListTlsRoutes', - request_serializer=tls_route.ListTlsRoutesRequest.serialize, - response_deserializer=tls_route.ListTlsRoutesResponse.deserialize, - ) - return self._stubs['list_tls_routes'] - - @property - def get_tls_route(self) -> Callable[ - [tls_route.GetTlsRouteRequest], - Awaitable[tls_route.TlsRoute]]: - r"""Return a callable for the get tls route method over gRPC. - - Gets details of a single TlsRoute. - - Returns: - Callable[[~.GetTlsRouteRequest], - Awaitable[~.TlsRoute]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tls_route' not in self._stubs: - self._stubs['get_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetTlsRoute', - request_serializer=tls_route.GetTlsRouteRequest.serialize, - response_deserializer=tls_route.TlsRoute.deserialize, - ) - return self._stubs['get_tls_route'] - - @property - def create_tls_route(self) -> Callable[ - [gcn_tls_route.CreateTlsRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create tls route method over gRPC. - - Creates a new TlsRoute in a given project and - location. - - Returns: - Callable[[~.CreateTlsRouteRequest], - 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_tls_route' not in self._stubs: - self._stubs['create_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateTlsRoute', - request_serializer=gcn_tls_route.CreateTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tls_route'] - - @property - def update_tls_route(self) -> Callable[ - [gcn_tls_route.UpdateTlsRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update tls route method over gRPC. - - Updates the parameters of a single TlsRoute. - - Returns: - Callable[[~.UpdateTlsRouteRequest], - 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_tls_route' not in self._stubs: - self._stubs['update_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateTlsRoute', - request_serializer=gcn_tls_route.UpdateTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tls_route'] - - @property - def delete_tls_route(self) -> Callable[ - [tls_route.DeleteTlsRouteRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete tls route method over gRPC. - - Deletes a single TlsRoute. - - Returns: - Callable[[~.DeleteTlsRouteRequest], - 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_tls_route' not in self._stubs: - self._stubs['delete_tls_route'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteTlsRoute', - request_serializer=tls_route.DeleteTlsRouteRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tls_route'] - - @property - def list_service_bindings(self) -> Callable[ - [service_binding.ListServiceBindingsRequest], - Awaitable[service_binding.ListServiceBindingsResponse]]: - r"""Return a callable for the list service bindings method over gRPC. - - Lists ServiceBinding in a given project and location. - - Returns: - Callable[[~.ListServiceBindingsRequest], - Awaitable[~.ListServiceBindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_bindings' not in self._stubs: - self._stubs['list_service_bindings'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListServiceBindings', - request_serializer=service_binding.ListServiceBindingsRequest.serialize, - response_deserializer=service_binding.ListServiceBindingsResponse.deserialize, - ) - return self._stubs['list_service_bindings'] - - @property - def get_service_binding(self) -> Callable[ - [service_binding.GetServiceBindingRequest], - Awaitable[service_binding.ServiceBinding]]: - r"""Return a callable for the get service binding method over gRPC. - - Gets details of a single ServiceBinding. - - Returns: - Callable[[~.GetServiceBindingRequest], - Awaitable[~.ServiceBinding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_binding' not in self._stubs: - self._stubs['get_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetServiceBinding', - request_serializer=service_binding.GetServiceBindingRequest.serialize, - response_deserializer=service_binding.ServiceBinding.deserialize, - ) - return self._stubs['get_service_binding'] - - @property - def create_service_binding(self) -> Callable[ - [gcn_service_binding.CreateServiceBindingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create service binding method over gRPC. - - Creates a new ServiceBinding in a given project and - location. - - Returns: - Callable[[~.CreateServiceBindingRequest], - 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_service_binding' not in self._stubs: - self._stubs['create_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateServiceBinding', - request_serializer=gcn_service_binding.CreateServiceBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service_binding'] - - @property - def delete_service_binding(self) -> Callable[ - [service_binding.DeleteServiceBindingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete service binding method over gRPC. - - Deletes a single ServiceBinding. - - Returns: - Callable[[~.DeleteServiceBindingRequest], - 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_service_binding' not in self._stubs: - self._stubs['delete_service_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteServiceBinding', - request_serializer=service_binding.DeleteServiceBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service_binding'] - - @property - def list_meshes(self) -> Callable[ - [mesh.ListMeshesRequest], - Awaitable[mesh.ListMeshesResponse]]: - r"""Return a callable for the list meshes method over gRPC. - - Lists Meshes in a given project and location. - - Returns: - Callable[[~.ListMeshesRequest], - Awaitable[~.ListMeshesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_meshes' not in self._stubs: - self._stubs['list_meshes'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/ListMeshes', - request_serializer=mesh.ListMeshesRequest.serialize, - response_deserializer=mesh.ListMeshesResponse.deserialize, - ) - return self._stubs['list_meshes'] - - @property - def get_mesh(self) -> Callable[ - [mesh.GetMeshRequest], - Awaitable[mesh.Mesh]]: - r"""Return a callable for the get mesh method over gRPC. - - Gets details of a single Mesh. - - Returns: - Callable[[~.GetMeshRequest], - Awaitable[~.Mesh]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mesh' not in self._stubs: - self._stubs['get_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/GetMesh', - request_serializer=mesh.GetMeshRequest.serialize, - response_deserializer=mesh.Mesh.deserialize, - ) - return self._stubs['get_mesh'] - - @property - def create_mesh(self) -> Callable[ - [gcn_mesh.CreateMeshRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create mesh method over gRPC. - - Creates a new Mesh in a given project and location. - - Returns: - Callable[[~.CreateMeshRequest], - 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_mesh' not in self._stubs: - self._stubs['create_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/CreateMesh', - request_serializer=gcn_mesh.CreateMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_mesh'] - - @property - def update_mesh(self) -> Callable[ - [gcn_mesh.UpdateMeshRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update mesh method over gRPC. - - Updates the parameters of a single Mesh. - - Returns: - Callable[[~.UpdateMeshRequest], - 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_mesh' not in self._stubs: - self._stubs['update_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/UpdateMesh', - request_serializer=gcn_mesh.UpdateMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_mesh'] - - @property - def delete_mesh(self) -> Callable[ - [mesh.DeleteMeshRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete mesh method over gRPC. - - Deletes a single Mesh. - - Returns: - Callable[[~.DeleteMeshRequest], - 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_mesh' not in self._stubs: - self._stubs['delete_mesh'] = self.grpc_channel.unary_unary( - '/google.cloud.networkservices.v1.NetworkServices/DeleteMesh', - request_serializer=mesh.DeleteMeshRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_mesh'] - - 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_endpoint_policies: gapic_v1.method_async.wrap_method( - self.list_endpoint_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_endpoint_policy: gapic_v1.method_async.wrap_method( - self.get_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_endpoint_policy: gapic_v1.method_async.wrap_method( - self.create_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_endpoint_policy: gapic_v1.method_async.wrap_method( - self.update_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_endpoint_policy: gapic_v1.method_async.wrap_method( - self.delete_endpoint_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_gateways: gapic_v1.method_async.wrap_method( - self.list_gateways, - default_timeout=None, - client_info=client_info, - ), - self.get_gateway: gapic_v1.method_async.wrap_method( - self.get_gateway, - default_timeout=None, - client_info=client_info, - ), - self.create_gateway: gapic_v1.method_async.wrap_method( - self.create_gateway, - default_timeout=None, - client_info=client_info, - ), - self.update_gateway: gapic_v1.method_async.wrap_method( - self.update_gateway, - default_timeout=None, - client_info=client_info, - ), - self.delete_gateway: gapic_v1.method_async.wrap_method( - self.delete_gateway, - default_timeout=None, - client_info=client_info, - ), - self.list_grpc_routes: gapic_v1.method_async.wrap_method( - self.list_grpc_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_grpc_route: gapic_v1.method_async.wrap_method( - self.get_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.create_grpc_route: gapic_v1.method_async.wrap_method( - self.create_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.update_grpc_route: gapic_v1.method_async.wrap_method( - self.update_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_grpc_route: gapic_v1.method_async.wrap_method( - self.delete_grpc_route, - default_timeout=None, - client_info=client_info, - ), - self.list_http_routes: gapic_v1.method_async.wrap_method( - self.list_http_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_http_route: gapic_v1.method_async.wrap_method( - self.get_http_route, - default_timeout=None, - client_info=client_info, - ), - self.create_http_route: gapic_v1.method_async.wrap_method( - self.create_http_route, - default_timeout=None, - client_info=client_info, - ), - self.update_http_route: gapic_v1.method_async.wrap_method( - self.update_http_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_http_route: gapic_v1.method_async.wrap_method( - self.delete_http_route, - default_timeout=None, - client_info=client_info, - ), - self.list_tcp_routes: gapic_v1.method_async.wrap_method( - self.list_tcp_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_tcp_route: gapic_v1.method_async.wrap_method( - self.get_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.create_tcp_route: gapic_v1.method_async.wrap_method( - self.create_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.update_tcp_route: gapic_v1.method_async.wrap_method( - self.update_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_tcp_route: gapic_v1.method_async.wrap_method( - self.delete_tcp_route, - default_timeout=None, - client_info=client_info, - ), - self.list_tls_routes: gapic_v1.method_async.wrap_method( - self.list_tls_routes, - default_timeout=None, - client_info=client_info, - ), - self.get_tls_route: gapic_v1.method_async.wrap_method( - self.get_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.create_tls_route: gapic_v1.method_async.wrap_method( - self.create_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.update_tls_route: gapic_v1.method_async.wrap_method( - self.update_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.delete_tls_route: gapic_v1.method_async.wrap_method( - self.delete_tls_route, - default_timeout=None, - client_info=client_info, - ), - self.list_service_bindings: gapic_v1.method_async.wrap_method( - self.list_service_bindings, - default_timeout=None, - client_info=client_info, - ), - self.get_service_binding: gapic_v1.method_async.wrap_method( - self.get_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.create_service_binding: gapic_v1.method_async.wrap_method( - self.create_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.delete_service_binding: gapic_v1.method_async.wrap_method( - self.delete_service_binding, - default_timeout=None, - client_info=client_info, - ), - self.list_meshes: gapic_v1.method_async.wrap_method( - self.list_meshes, - default_timeout=None, - client_info=client_info, - ), - self.get_mesh: gapic_v1.method_async.wrap_method( - self.get_mesh, - default_timeout=None, - client_info=client_info, - ), - self.create_mesh: gapic_v1.method_async.wrap_method( - self.create_mesh, - default_timeout=None, - client_info=client_info, - ), - self.update_mesh: gapic_v1.method_async.wrap_method( - self.update_mesh, - default_timeout=None, - client_info=client_info, - ), - self.delete_mesh: gapic_v1.method_async.wrap_method( - self.delete_mesh, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'NetworkServicesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py deleted file mode 100644 index fd6f01e2dfee..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/services/network_services/transports/rest.py +++ /dev/null @@ -1,5574 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -from google.longrunning import operations_pb2 # type: ignore - -from .base import NetworkServicesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class NetworkServicesRestInterceptor: - """Interceptor for NetworkServices. - - 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 NetworkServicesRestTransport. - - .. code-block:: python - class MyCustomNetworkServicesInterceptor(NetworkServicesRestInterceptor): - def pre_create_endpoint_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_endpoint_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_grpc_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_grpc_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_http_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_http_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_mesh(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_mesh(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_service_binding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_service_binding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_tcp_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_tcp_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_tls_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_tls_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_endpoint_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_endpoint_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_grpc_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_grpc_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_http_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_http_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_mesh(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_mesh(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_service_binding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_service_binding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_tcp_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_tcp_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_tls_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_tls_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_endpoint_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_endpoint_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_grpc_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_grpc_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_http_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_http_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_mesh(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_mesh(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_service_binding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_service_binding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_tcp_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_tcp_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_tls_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_tls_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_endpoint_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_endpoint_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_gateways(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_gateways(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_grpc_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_grpc_routes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_http_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_http_routes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_meshes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_meshes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_service_bindings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_service_bindings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tcp_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tcp_routes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tls_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tls_routes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_endpoint_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_endpoint_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_grpc_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_grpc_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_http_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_http_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_mesh(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_mesh(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_tcp_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_tcp_route(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_tls_route(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_tls_route(self, response): - logging.log(f"Received response: {response}") - return response - - transport = NetworkServicesRestTransport(interceptor=MyCustomNetworkServicesInterceptor()) - client = NetworkServicesClient(transport=transport) - - - """ - def pre_create_endpoint_policy(self, request: gcn_endpoint_policy.CreateEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_endpoint_policy.CreateEndpointPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_endpoint_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_endpoint_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_gateway(self, request: gcn_gateway.CreateGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_gateway.CreateGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_gateway - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_grpc_route(self, request: gcn_grpc_route.CreateGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_grpc_route.CreateGrpcRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_grpc_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_grpc_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_http_route(self, request: gcn_http_route.CreateHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_http_route.CreateHttpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_http_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_http_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_mesh(self, request: gcn_mesh.CreateMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_mesh.CreateMeshRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_mesh - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_mesh - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_service_binding(self, request: gcn_service_binding.CreateServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_service_binding.CreateServiceBindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_service_binding - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_service_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_service_binding - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_tcp_route(self, request: gcn_tcp_route.CreateTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tcp_route.CreateTcpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_tcp_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_tcp_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_create_tls_route(self, request: gcn_tls_route.CreateTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tls_route.CreateTlsRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_tls_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_create_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_tls_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_endpoint_policy(self, request: endpoint_policy.DeleteEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.DeleteEndpointPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_endpoint_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_endpoint_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_gateway(self, request: gateway.DeleteGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.DeleteGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_gateway - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_grpc_route(self, request: grpc_route.DeleteGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.DeleteGrpcRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_grpc_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_grpc_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_http_route(self, request: http_route.DeleteHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.DeleteHttpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_http_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_http_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_mesh(self, request: mesh.DeleteMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.DeleteMeshRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_mesh - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_mesh - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_service_binding(self, request: service_binding.DeleteServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.DeleteServiceBindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_service_binding - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_service_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_service_binding - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_tcp_route(self, request: tcp_route.DeleteTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.DeleteTcpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_tcp_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_tcp_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_tls_route(self, request: tls_route.DeleteTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.DeleteTlsRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_tls_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_delete_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_tls_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_endpoint_policy(self, request: endpoint_policy.GetEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.GetEndpointPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_endpoint_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_endpoint_policy(self, response: endpoint_policy.EndpointPolicy) -> endpoint_policy.EndpointPolicy: - """Post-rpc interceptor for get_endpoint_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_gateway(self, request: gateway.GetGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.GetGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_gateway(self, response: gateway.Gateway) -> gateway.Gateway: - """Post-rpc interceptor for get_gateway - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_grpc_route(self, request: grpc_route.GetGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.GetGrpcRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_grpc_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_grpc_route(self, response: grpc_route.GrpcRoute) -> grpc_route.GrpcRoute: - """Post-rpc interceptor for get_grpc_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_http_route(self, request: http_route.GetHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.GetHttpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_http_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_http_route(self, response: http_route.HttpRoute) -> http_route.HttpRoute: - """Post-rpc interceptor for get_http_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_mesh(self, request: mesh.GetMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.GetMeshRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_mesh - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_mesh(self, response: mesh.Mesh) -> mesh.Mesh: - """Post-rpc interceptor for get_mesh - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_service_binding(self, request: service_binding.GetServiceBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.GetServiceBindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_service_binding - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_service_binding(self, response: service_binding.ServiceBinding) -> service_binding.ServiceBinding: - """Post-rpc interceptor for get_service_binding - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_tcp_route(self, request: tcp_route.GetTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.GetTcpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_tcp_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_tcp_route(self, response: tcp_route.TcpRoute) -> tcp_route.TcpRoute: - """Post-rpc interceptor for get_tcp_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_tls_route(self, request: tls_route.GetTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.GetTlsRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_tls_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_get_tls_route(self, response: tls_route.TlsRoute) -> tls_route.TlsRoute: - """Post-rpc interceptor for get_tls_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_endpoint_policies(self, request: endpoint_policy.ListEndpointPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[endpoint_policy.ListEndpointPoliciesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_endpoint_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_endpoint_policies(self, response: endpoint_policy.ListEndpointPoliciesResponse) -> endpoint_policy.ListEndpointPoliciesResponse: - """Post-rpc interceptor for list_endpoint_policies - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_gateways(self, request: gateway.ListGatewaysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gateway.ListGatewaysRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_gateways - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_gateways(self, response: gateway.ListGatewaysResponse) -> gateway.ListGatewaysResponse: - """Post-rpc interceptor for list_gateways - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_grpc_routes(self, request: grpc_route.ListGrpcRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[grpc_route.ListGrpcRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_grpc_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_grpc_routes(self, response: grpc_route.ListGrpcRoutesResponse) -> grpc_route.ListGrpcRoutesResponse: - """Post-rpc interceptor for list_grpc_routes - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_http_routes(self, request: http_route.ListHttpRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[http_route.ListHttpRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_http_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_http_routes(self, response: http_route.ListHttpRoutesResponse) -> http_route.ListHttpRoutesResponse: - """Post-rpc interceptor for list_http_routes - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_meshes(self, request: mesh.ListMeshesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[mesh.ListMeshesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_meshes - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_meshes(self, response: mesh.ListMeshesResponse) -> mesh.ListMeshesResponse: - """Post-rpc interceptor for list_meshes - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_service_bindings(self, request: service_binding.ListServiceBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_binding.ListServiceBindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_service_bindings - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_service_bindings(self, response: service_binding.ListServiceBindingsResponse) -> service_binding.ListServiceBindingsResponse: - """Post-rpc interceptor for list_service_bindings - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_tcp_routes(self, request: tcp_route.ListTcpRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tcp_route.ListTcpRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tcp_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_tcp_routes(self, response: tcp_route.ListTcpRoutesResponse) -> tcp_route.ListTcpRoutesResponse: - """Post-rpc interceptor for list_tcp_routes - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_tls_routes(self, request: tls_route.ListTlsRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tls_route.ListTlsRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tls_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_list_tls_routes(self, response: tls_route.ListTlsRoutesResponse) -> tls_route.ListTlsRoutesResponse: - """Post-rpc interceptor for list_tls_routes - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_endpoint_policy(self, request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_endpoint_policy.UpdateEndpointPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_endpoint_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_endpoint_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_endpoint_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_gateway(self, request: gcn_gateway.UpdateGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_gateway.UpdateGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_gateway(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_gateway - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_grpc_route(self, request: gcn_grpc_route.UpdateGrpcRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_grpc_route.UpdateGrpcRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_grpc_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_grpc_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_grpc_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_http_route(self, request: gcn_http_route.UpdateHttpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_http_route.UpdateHttpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_http_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_http_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_http_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_mesh(self, request: gcn_mesh.UpdateMeshRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_mesh.UpdateMeshRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_mesh - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_mesh(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_mesh - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_tcp_route(self, request: gcn_tcp_route.UpdateTcpRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tcp_route.UpdateTcpRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_tcp_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_tcp_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_tcp_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - def pre_update_tls_route(self, request: gcn_tls_route.UpdateTlsRouteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcn_tls_route.UpdateTlsRouteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_tls_route - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices server. - """ - return request, metadata - - def post_update_tls_route(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_tls_route - - Override in a subclass to manipulate the response - after it is returned by the NetworkServices server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkServices 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 NetworkServices server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class NetworkServicesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: NetworkServicesRestInterceptor - - -class NetworkServicesRestTransport(NetworkServicesTransport): - """REST backend transport for NetworkServices. - - 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 = 'networkservices.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[NetworkServicesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networkservices.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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or NetworkServicesRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateEndpointPolicy(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateEndpointPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "endpointPolicyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_endpoint_policy.CreateEndpointPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create endpoint policy method over HTTP. - - Args: - request (~.gcn_endpoint_policy.CreateEndpointPolicyRequest): - The request object. Request used with the - CreateEndpointPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/endpointPolicies', - 'body': 'endpoint_policy', - }, - ] - request, metadata = self._interceptor.pre_create_endpoint_policy(request, metadata) - pb_request = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_endpoint_policy(resp) - return resp - - class _CreateGateway(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "gatewayId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_gateway.CreateGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create gateway method over HTTP. - - Args: - request (~.gcn_gateway.CreateGatewayRequest): - The request object. Request used by the CreateGateway - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/gateways', - 'body': 'gateway', - }, - ] - request, metadata = self._interceptor.pre_create_gateway(request, metadata) - pb_request = gcn_gateway.CreateGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_gateway(resp) - return resp - - class _CreateGrpcRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateGrpcRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "grpcRouteId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_grpc_route.CreateGrpcRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create grpc route method over HTTP. - - Args: - request (~.gcn_grpc_route.CreateGrpcRouteRequest): - The request object. Request used by the CreateGrpcRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/grpcRoutes', - 'body': 'grpc_route', - }, - ] - request, metadata = self._interceptor.pre_create_grpc_route(request, metadata) - pb_request = gcn_grpc_route.CreateGrpcRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_grpc_route(resp) - return resp - - class _CreateHttpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateHttpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "httpRouteId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_http_route.CreateHttpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create http route method over HTTP. - - Args: - request (~.gcn_http_route.CreateHttpRouteRequest): - The request object. Request used by the HttpRoute method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/httpRoutes', - 'body': 'http_route', - }, - ] - request, metadata = self._interceptor.pre_create_http_route(request, metadata) - pb_request = gcn_http_route.CreateHttpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_http_route(resp) - return resp - - class _CreateMesh(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateMesh") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "meshId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_mesh.CreateMeshRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create mesh method over HTTP. - - Args: - request (~.gcn_mesh.CreateMeshRequest): - The request object. Request used by the CreateMesh - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/meshes', - 'body': 'mesh', - }, - ] - request, metadata = self._interceptor.pre_create_mesh(request, metadata) - pb_request = gcn_mesh.CreateMeshRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_mesh(resp) - return resp - - class _CreateServiceBinding(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateServiceBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "serviceBindingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_service_binding.CreateServiceBindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create service binding method over HTTP. - - Args: - request (~.gcn_service_binding.CreateServiceBindingRequest): - The request object. Request used by the ServiceBinding - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/serviceBindings', - 'body': 'service_binding', - }, - ] - request, metadata = self._interceptor.pre_create_service_binding(request, metadata) - pb_request = gcn_service_binding.CreateServiceBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_service_binding(resp) - return resp - - class _CreateTcpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateTcpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "tcpRouteId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_tcp_route.CreateTcpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create tcp route method over HTTP. - - Args: - request (~.gcn_tcp_route.CreateTcpRouteRequest): - The request object. Request used by the TcpRoute method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/tcpRoutes', - 'body': 'tcp_route', - }, - ] - request, metadata = self._interceptor.pre_create_tcp_route(request, metadata) - pb_request = gcn_tcp_route.CreateTcpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_tcp_route(resp) - return resp - - class _CreateTlsRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("CreateTlsRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "tlsRouteId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_tls_route.CreateTlsRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create tls route method over HTTP. - - Args: - request (~.gcn_tls_route.CreateTlsRouteRequest): - The request object. Request used by the TlsRoute method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/tlsRoutes', - 'body': 'tls_route', - }, - ] - request, metadata = self._interceptor.pre_create_tls_route(request, metadata) - pb_request = gcn_tls_route.CreateTlsRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_tls_route(resp) - return resp - - class _DeleteEndpointPolicy(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteEndpointPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: endpoint_policy.DeleteEndpointPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete endpoint policy method over HTTP. - - Args: - request (~.endpoint_policy.DeleteEndpointPolicyRequest): - The request object. Request used with the - DeleteEndpointPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/endpointPolicies/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_endpoint_policy(request, metadata) - pb_request = endpoint_policy.DeleteEndpointPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_endpoint_policy(resp) - return resp - - class _DeleteGateway(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gateway.DeleteGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete gateway method over HTTP. - - Args: - request (~.gateway.DeleteGatewayRequest): - The request object. Request used by the DeleteGateway - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/gateways/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_gateway(request, metadata) - pb_request = gateway.DeleteGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_gateway(resp) - return resp - - class _DeleteGrpcRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteGrpcRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: grpc_route.DeleteGrpcRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete grpc route method over HTTP. - - Args: - request (~.grpc_route.DeleteGrpcRouteRequest): - The request object. Request used by the DeleteGrpcRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/grpcRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_grpc_route(request, metadata) - pb_request = grpc_route.DeleteGrpcRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_grpc_route(resp) - return resp - - class _DeleteHttpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteHttpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: http_route.DeleteHttpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete http route method over HTTP. - - Args: - request (~.http_route.DeleteHttpRouteRequest): - The request object. Request used by the DeleteHttpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/httpRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_http_route(request, metadata) - pb_request = http_route.DeleteHttpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_http_route(resp) - return resp - - class _DeleteMesh(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteMesh") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: mesh.DeleteMeshRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete mesh method over HTTP. - - Args: - request (~.mesh.DeleteMeshRequest): - The request object. Request used by the DeleteMesh - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/meshes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_mesh(request, metadata) - pb_request = mesh.DeleteMeshRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_mesh(resp) - return resp - - class _DeleteServiceBinding(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteServiceBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: service_binding.DeleteServiceBindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete service binding method over HTTP. - - Args: - request (~.service_binding.DeleteServiceBindingRequest): - The request object. Request used by the - DeleteServiceBinding method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/serviceBindings/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_service_binding(request, metadata) - pb_request = service_binding.DeleteServiceBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_service_binding(resp) - return resp - - class _DeleteTcpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteTcpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tcp_route.DeleteTcpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete tcp route method over HTTP. - - Args: - request (~.tcp_route.DeleteTcpRouteRequest): - The request object. Request used by the DeleteTcpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/tcpRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_tcp_route(request, metadata) - pb_request = tcp_route.DeleteTcpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_tcp_route(resp) - return resp - - class _DeleteTlsRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("DeleteTlsRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tls_route.DeleteTlsRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete tls route method over HTTP. - - Args: - request (~.tls_route.DeleteTlsRouteRequest): - The request object. Request used by the DeleteTlsRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/tlsRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_tls_route(request, metadata) - pb_request = tls_route.DeleteTlsRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_tls_route(resp) - return resp - - class _GetEndpointPolicy(NetworkServicesRestStub): - def __hash__(self): - return hash("GetEndpointPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: endpoint_policy.GetEndpointPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> endpoint_policy.EndpointPolicy: - r"""Call the get endpoint policy method over HTTP. - - Args: - request (~.endpoint_policy.GetEndpointPolicyRequest): - The request object. Request used with the - GetEndpointPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.endpoint_policy.EndpointPolicy: - EndpointPolicy is a resource that - helps apply desired configuration on the - endpoints that match specific criteria. - For example, this resource can be used - to apply "authentication config" an all - endpoints that serve on port 8080. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/endpointPolicies/*}', - }, - ] - request, metadata = self._interceptor.pre_get_endpoint_policy(request, metadata) - pb_request = endpoint_policy.GetEndpointPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = endpoint_policy.EndpointPolicy() - pb_resp = endpoint_policy.EndpointPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_endpoint_policy(resp) - return resp - - class _GetGateway(NetworkServicesRestStub): - def __hash__(self): - return hash("GetGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gateway.GetGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gateway.Gateway: - r"""Call the get gateway method over HTTP. - - Args: - request (~.gateway.GetGatewayRequest): - The request object. Request used by the GetGateway - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gateway.Gateway: - Gateway represents the configuration - for a proxy, typically a load balancer. - It captures the ip:port over which the - services are exposed by the proxy, along - with any policy configurations. Routes - have reference to to Gateways to dictate - how requests should be routed by this - Gateway. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/gateways/*}', - }, - ] - request, metadata = self._interceptor.pre_get_gateway(request, metadata) - pb_request = gateway.GetGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gateway.Gateway() - pb_resp = gateway.Gateway.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_gateway(resp) - return resp - - class _GetGrpcRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("GetGrpcRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: grpc_route.GetGrpcRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> grpc_route.GrpcRoute: - r"""Call the get grpc route method over HTTP. - - Args: - request (~.grpc_route.GetGrpcRouteRequest): - The request object. Request used by the GetGrpcRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.grpc_route.GrpcRoute: - GrpcRoute is the resource defining - how gRPC traffic routed by a Mesh or - Gateway resource is routed. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/grpcRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_grpc_route(request, metadata) - pb_request = grpc_route.GetGrpcRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = grpc_route.GrpcRoute() - pb_resp = grpc_route.GrpcRoute.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_grpc_route(resp) - return resp - - class _GetHttpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("GetHttpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: http_route.GetHttpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> http_route.HttpRoute: - r"""Call the get http route method over HTTP. - - Args: - request (~.http_route.GetHttpRouteRequest): - The request object. Request used by the GetHttpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.http_route.HttpRoute: - HttpRoute is the resource defining - how HTTP traffic should be routed by a - Mesh or Gateway resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/httpRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_http_route(request, metadata) - pb_request = http_route.GetHttpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = http_route.HttpRoute() - pb_resp = http_route.HttpRoute.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_http_route(resp) - return resp - - class _GetMesh(NetworkServicesRestStub): - def __hash__(self): - return hash("GetMesh") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: mesh.GetMeshRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mesh.Mesh: - r"""Call the get mesh method over HTTP. - - Args: - request (~.mesh.GetMeshRequest): - The request object. Request used by the GetMesh method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mesh.Mesh: - Mesh represents a logical - configuration grouping for workload to - workload communication within a service - mesh. Routes that point to mesh dictate - how requests are routed within this - logical mesh boundary. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/meshes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_mesh(request, metadata) - pb_request = mesh.GetMeshRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mesh.Mesh() - pb_resp = mesh.Mesh.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_mesh(resp) - return resp - - class _GetServiceBinding(NetworkServicesRestStub): - def __hash__(self): - return hash("GetServiceBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: service_binding.GetServiceBindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_binding.ServiceBinding: - r"""Call the get service binding method over HTTP. - - Args: - request (~.service_binding.GetServiceBindingRequest): - The request object. Request used by the GetServiceBinding - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service_binding.ServiceBinding: - ServiceBinding is the resource that - defines a Service Directory Service to - be used in a BackendService resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/serviceBindings/*}', - }, - ] - request, metadata = self._interceptor.pre_get_service_binding(request, metadata) - pb_request = service_binding.GetServiceBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_binding.ServiceBinding() - pb_resp = service_binding.ServiceBinding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_service_binding(resp) - return resp - - class _GetTcpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("GetTcpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tcp_route.GetTcpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tcp_route.TcpRoute: - r"""Call the get tcp route method over HTTP. - - Args: - request (~.tcp_route.GetTcpRouteRequest): - The request object. Request used by the GetTcpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tcp_route.TcpRoute: - TcpRoute is the resource defining how - TCP traffic should be routed by a - Mesh/Gateway resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/tcpRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_tcp_route(request, metadata) - pb_request = tcp_route.GetTcpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tcp_route.TcpRoute() - pb_resp = tcp_route.TcpRoute.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_tcp_route(resp) - return resp - - class _GetTlsRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("GetTlsRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tls_route.GetTlsRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tls_route.TlsRoute: - r"""Call the get tls route method over HTTP. - - Args: - request (~.tls_route.GetTlsRouteRequest): - The request object. Request used by the GetTlsRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tls_route.TlsRoute: - TlsRoute defines how traffic should - be routed based on SNI and other - matching L3 attributes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/tlsRoutes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_tls_route(request, metadata) - pb_request = tls_route.GetTlsRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tls_route.TlsRoute() - pb_resp = tls_route.TlsRoute.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_tls_route(resp) - return resp - - class _ListEndpointPolicies(NetworkServicesRestStub): - def __hash__(self): - return hash("ListEndpointPolicies") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: endpoint_policy.ListEndpointPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> endpoint_policy.ListEndpointPoliciesResponse: - r"""Call the list endpoint policies method over HTTP. - - Args: - request (~.endpoint_policy.ListEndpointPoliciesRequest): - The request object. Request used with the - ListEndpointPolicies method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.endpoint_policy.ListEndpointPoliciesResponse: - Response returned by the - ListEndpointPolicies method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/endpointPolicies', - }, - ] - request, metadata = self._interceptor.pre_list_endpoint_policies(request, metadata) - pb_request = endpoint_policy.ListEndpointPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = endpoint_policy.ListEndpointPoliciesResponse() - pb_resp = endpoint_policy.ListEndpointPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_endpoint_policies(resp) - return resp - - class _ListGateways(NetworkServicesRestStub): - def __hash__(self): - return hash("ListGateways") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gateway.ListGatewaysRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gateway.ListGatewaysResponse: - r"""Call the list gateways method over HTTP. - - Args: - request (~.gateway.ListGatewaysRequest): - The request object. Request used with the ListGateways - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gateway.ListGatewaysResponse: - Response returned by the ListGateways - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/gateways', - }, - ] - request, metadata = self._interceptor.pre_list_gateways(request, metadata) - pb_request = gateway.ListGatewaysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gateway.ListGatewaysResponse() - pb_resp = gateway.ListGatewaysResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_gateways(resp) - return resp - - class _ListGrpcRoutes(NetworkServicesRestStub): - def __hash__(self): - return hash("ListGrpcRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: grpc_route.ListGrpcRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> grpc_route.ListGrpcRoutesResponse: - r"""Call the list grpc routes method over HTTP. - - Args: - request (~.grpc_route.ListGrpcRoutesRequest): - The request object. Request used with the ListGrpcRoutes - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.grpc_route.ListGrpcRoutesResponse: - Response returned by the - ListGrpcRoutes method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/grpcRoutes', - }, - ] - request, metadata = self._interceptor.pre_list_grpc_routes(request, metadata) - pb_request = grpc_route.ListGrpcRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = grpc_route.ListGrpcRoutesResponse() - pb_resp = grpc_route.ListGrpcRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_grpc_routes(resp) - return resp - - class _ListHttpRoutes(NetworkServicesRestStub): - def __hash__(self): - return hash("ListHttpRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: http_route.ListHttpRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> http_route.ListHttpRoutesResponse: - r"""Call the list http routes method over HTTP. - - Args: - request (~.http_route.ListHttpRoutesRequest): - The request object. Request used with the ListHttpRoutes - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.http_route.ListHttpRoutesResponse: - Response returned by the - ListHttpRoutes method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/httpRoutes', - }, - ] - request, metadata = self._interceptor.pre_list_http_routes(request, metadata) - pb_request = http_route.ListHttpRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = http_route.ListHttpRoutesResponse() - pb_resp = http_route.ListHttpRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_http_routes(resp) - return resp - - class _ListMeshes(NetworkServicesRestStub): - def __hash__(self): - return hash("ListMeshes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: mesh.ListMeshesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mesh.ListMeshesResponse: - r"""Call the list meshes method over HTTP. - - Args: - request (~.mesh.ListMeshesRequest): - The request object. Request used with the ListMeshes - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mesh.ListMeshesResponse: - Response returned by the ListMeshes - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/meshes', - }, - ] - request, metadata = self._interceptor.pre_list_meshes(request, metadata) - pb_request = mesh.ListMeshesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mesh.ListMeshesResponse() - pb_resp = mesh.ListMeshesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_meshes(resp) - return resp - - class _ListServiceBindings(NetworkServicesRestStub): - def __hash__(self): - return hash("ListServiceBindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: service_binding.ListServiceBindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_binding.ListServiceBindingsResponse: - r"""Call the list service bindings method over HTTP. - - Args: - request (~.service_binding.ListServiceBindingsRequest): - The request object. Request used with the - ListServiceBindings method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service_binding.ListServiceBindingsResponse: - Response returned by the - ListServiceBindings method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/serviceBindings', - }, - ] - request, metadata = self._interceptor.pre_list_service_bindings(request, metadata) - pb_request = service_binding.ListServiceBindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_binding.ListServiceBindingsResponse() - pb_resp = service_binding.ListServiceBindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_service_bindings(resp) - return resp - - class _ListTcpRoutes(NetworkServicesRestStub): - def __hash__(self): - return hash("ListTcpRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tcp_route.ListTcpRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tcp_route.ListTcpRoutesResponse: - r"""Call the list tcp routes method over HTTP. - - Args: - request (~.tcp_route.ListTcpRoutesRequest): - The request object. Request used with the ListTcpRoutes - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tcp_route.ListTcpRoutesResponse: - Response returned by the - ListTcpRoutes method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/tcpRoutes', - }, - ] - request, metadata = self._interceptor.pre_list_tcp_routes(request, metadata) - pb_request = tcp_route.ListTcpRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tcp_route.ListTcpRoutesResponse() - pb_resp = tcp_route.ListTcpRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tcp_routes(resp) - return resp - - class _ListTlsRoutes(NetworkServicesRestStub): - def __hash__(self): - return hash("ListTlsRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tls_route.ListTlsRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tls_route.ListTlsRoutesResponse: - r"""Call the list tls routes method over HTTP. - - Args: - request (~.tls_route.ListTlsRoutesRequest): - The request object. Request used with the ListTlsRoutes - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tls_route.ListTlsRoutesResponse: - Response returned by the - ListTlsRoutes method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/tlsRoutes', - }, - ] - request, metadata = self._interceptor.pre_list_tls_routes(request, metadata) - pb_request = tls_route.ListTlsRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tls_route.ListTlsRoutesResponse() - pb_resp = tls_route.ListTlsRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tls_routes(resp) - return resp - - class _UpdateEndpointPolicy(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateEndpointPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update endpoint policy method over HTTP. - - Args: - request (~.gcn_endpoint_policy.UpdateEndpointPolicyRequest): - The request object. Request used with the - UpdateEndpointPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}', - 'body': 'endpoint_policy', - }, - ] - request, metadata = self._interceptor.pre_update_endpoint_policy(request, metadata) - pb_request = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_endpoint_policy(resp) - return resp - - class _UpdateGateway(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_gateway.UpdateGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update gateway method over HTTP. - - Args: - request (~.gcn_gateway.UpdateGatewayRequest): - The request object. Request used by the UpdateGateway - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{gateway.name=projects/*/locations/*/gateways/*}', - 'body': 'gateway', - }, - ] - request, metadata = self._interceptor.pre_update_gateway(request, metadata) - pb_request = gcn_gateway.UpdateGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_gateway(resp) - return resp - - class _UpdateGrpcRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateGrpcRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_grpc_route.UpdateGrpcRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update grpc route method over HTTP. - - Args: - request (~.gcn_grpc_route.UpdateGrpcRouteRequest): - The request object. Request used by the UpdateGrpcRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}', - 'body': 'grpc_route', - }, - ] - request, metadata = self._interceptor.pre_update_grpc_route(request, metadata) - pb_request = gcn_grpc_route.UpdateGrpcRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_grpc_route(resp) - return resp - - class _UpdateHttpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateHttpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_http_route.UpdateHttpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update http route method over HTTP. - - Args: - request (~.gcn_http_route.UpdateHttpRouteRequest): - The request object. Request used by the UpdateHttpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{http_route.name=projects/*/locations/*/httpRoutes/*}', - 'body': 'http_route', - }, - ] - request, metadata = self._interceptor.pre_update_http_route(request, metadata) - pb_request = gcn_http_route.UpdateHttpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_http_route(resp) - return resp - - class _UpdateMesh(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateMesh") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_mesh.UpdateMeshRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update mesh method over HTTP. - - Args: - request (~.gcn_mesh.UpdateMeshRequest): - The request object. Request used by the UpdateMesh - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{mesh.name=projects/*/locations/*/meshes/*}', - 'body': 'mesh', - }, - ] - request, metadata = self._interceptor.pre_update_mesh(request, metadata) - pb_request = gcn_mesh.UpdateMeshRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_mesh(resp) - return resp - - class _UpdateTcpRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateTcpRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_tcp_route.UpdateTcpRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update tcp route method over HTTP. - - Args: - request (~.gcn_tcp_route.UpdateTcpRouteRequest): - The request object. Request used by the UpdateTcpRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}', - 'body': 'tcp_route', - }, - ] - request, metadata = self._interceptor.pre_update_tcp_route(request, metadata) - pb_request = gcn_tcp_route.UpdateTcpRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_tcp_route(resp) - return resp - - class _UpdateTlsRoute(NetworkServicesRestStub): - def __hash__(self): - return hash("UpdateTlsRoute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcn_tls_route.UpdateTlsRouteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update tls route method over HTTP. - - Args: - request (~.gcn_tls_route.UpdateTlsRouteRequest): - The request object. Request used by the UpdateTlsRoute - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{tls_route.name=projects/*/locations/*/tlsRoutes/*}', - 'body': 'tls_route', - }, - ] - request, metadata = self._interceptor.pre_update_tls_route(request, metadata) - pb_request = gcn_tls_route.UpdateTlsRouteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_tls_route(resp) - return resp - - @property - def create_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.CreateEndpointPolicyRequest], - 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._CreateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_gateway(self) -> Callable[ - [gcn_gateway.CreateGatewayRequest], - 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._CreateGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_grpc_route(self) -> Callable[ - [gcn_grpc_route.CreateGrpcRouteRequest], - 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._CreateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_http_route(self) -> Callable[ - [gcn_http_route.CreateHttpRouteRequest], - 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._CreateHttpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_mesh(self) -> Callable[ - [gcn_mesh.CreateMeshRequest], - 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._CreateMesh(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_service_binding(self) -> Callable[ - [gcn_service_binding.CreateServiceBindingRequest], - 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._CreateServiceBinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_tcp_route(self) -> Callable[ - [gcn_tcp_route.CreateTcpRouteRequest], - 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._CreateTcpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_tls_route(self) -> Callable[ - [gcn_tls_route.CreateTlsRouteRequest], - 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._CreateTlsRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_endpoint_policy(self) -> Callable[ - [endpoint_policy.DeleteEndpointPolicyRequest], - 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._DeleteEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_gateway(self) -> Callable[ - [gateway.DeleteGatewayRequest], - 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._DeleteGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_grpc_route(self) -> Callable[ - [grpc_route.DeleteGrpcRouteRequest], - 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._DeleteGrpcRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_http_route(self) -> Callable[ - [http_route.DeleteHttpRouteRequest], - 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._DeleteHttpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_mesh(self) -> Callable[ - [mesh.DeleteMeshRequest], - 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._DeleteMesh(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_service_binding(self) -> Callable[ - [service_binding.DeleteServiceBindingRequest], - 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._DeleteServiceBinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_tcp_route(self) -> Callable[ - [tcp_route.DeleteTcpRouteRequest], - 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._DeleteTcpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_tls_route(self) -> Callable[ - [tls_route.DeleteTlsRouteRequest], - 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._DeleteTlsRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_endpoint_policy(self) -> Callable[ - [endpoint_policy.GetEndpointPolicyRequest], - endpoint_policy.EndpointPolicy]: - # 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._GetEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_gateway(self) -> Callable[ - [gateway.GetGatewayRequest], - gateway.Gateway]: - # 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._GetGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_grpc_route(self) -> Callable[ - [grpc_route.GetGrpcRouteRequest], - grpc_route.GrpcRoute]: - # 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._GetGrpcRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_http_route(self) -> Callable[ - [http_route.GetHttpRouteRequest], - http_route.HttpRoute]: - # 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._GetHttpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_mesh(self) -> Callable[ - [mesh.GetMeshRequest], - mesh.Mesh]: - # 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._GetMesh(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_service_binding(self) -> Callable[ - [service_binding.GetServiceBindingRequest], - service_binding.ServiceBinding]: - # 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._GetServiceBinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_tcp_route(self) -> Callable[ - [tcp_route.GetTcpRouteRequest], - tcp_route.TcpRoute]: - # 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._GetTcpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_tls_route(self) -> Callable[ - [tls_route.GetTlsRouteRequest], - tls_route.TlsRoute]: - # 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._GetTlsRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_endpoint_policies(self) -> Callable[ - [endpoint_policy.ListEndpointPoliciesRequest], - endpoint_policy.ListEndpointPoliciesResponse]: - # 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._ListEndpointPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_gateways(self) -> Callable[ - [gateway.ListGatewaysRequest], - gateway.ListGatewaysResponse]: - # 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._ListGateways(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_grpc_routes(self) -> Callable[ - [grpc_route.ListGrpcRoutesRequest], - grpc_route.ListGrpcRoutesResponse]: - # 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._ListGrpcRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_http_routes(self) -> Callable[ - [http_route.ListHttpRoutesRequest], - http_route.ListHttpRoutesResponse]: - # 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._ListHttpRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_meshes(self) -> Callable[ - [mesh.ListMeshesRequest], - mesh.ListMeshesResponse]: - # 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._ListMeshes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_service_bindings(self) -> Callable[ - [service_binding.ListServiceBindingsRequest], - service_binding.ListServiceBindingsResponse]: - # 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._ListServiceBindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tcp_routes(self) -> Callable[ - [tcp_route.ListTcpRoutesRequest], - tcp_route.ListTcpRoutesResponse]: - # 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._ListTcpRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tls_routes(self) -> Callable[ - [tls_route.ListTlsRoutesRequest], - tls_route.ListTlsRoutesResponse]: - # 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._ListTlsRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_endpoint_policy(self) -> Callable[ - [gcn_endpoint_policy.UpdateEndpointPolicyRequest], - 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._UpdateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_gateway(self) -> Callable[ - [gcn_gateway.UpdateGatewayRequest], - 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._UpdateGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_grpc_route(self) -> Callable[ - [gcn_grpc_route.UpdateGrpcRouteRequest], - 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._UpdateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_http_route(self) -> Callable[ - [gcn_http_route.UpdateHttpRouteRequest], - 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._UpdateHttpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_mesh(self) -> Callable[ - [gcn_mesh.UpdateMeshRequest], - 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._UpdateMesh(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_tcp_route(self) -> Callable[ - [gcn_tcp_route.UpdateTcpRouteRequest], - 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._UpdateTcpRoute(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_tls_route(self) -> Callable[ - [gcn_tls_route.UpdateTlsRouteRequest], - 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._UpdateTlsRoute(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(NetworkServicesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(NetworkServicesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(NetworkServicesRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(NetworkServicesRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(NetworkServicesRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serviceBindings/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/meshes/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/gateways/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(NetworkServicesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(NetworkServicesRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(NetworkServicesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(NetworkServicesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'NetworkServicesRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py deleted file mode 100644 index 4685b6bd1d61..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/__init__.py +++ /dev/null @@ -1,188 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .common import ( - EndpointMatcher, - OperationMetadata, - TrafficPortSelector, -) -from .dep import ( - CreateLbRouteExtensionRequest, - CreateLbTrafficExtensionRequest, - DeleteLbRouteExtensionRequest, - DeleteLbTrafficExtensionRequest, - ExtensionChain, - GetLbRouteExtensionRequest, - GetLbTrafficExtensionRequest, - LbRouteExtension, - LbTrafficExtension, - ListLbRouteExtensionsRequest, - ListLbRouteExtensionsResponse, - ListLbTrafficExtensionsRequest, - ListLbTrafficExtensionsResponse, - UpdateLbRouteExtensionRequest, - UpdateLbTrafficExtensionRequest, - EventType, - LoadBalancingScheme, -) -from .endpoint_policy import ( - CreateEndpointPolicyRequest, - DeleteEndpointPolicyRequest, - EndpointPolicy, - GetEndpointPolicyRequest, - ListEndpointPoliciesRequest, - ListEndpointPoliciesResponse, - UpdateEndpointPolicyRequest, -) -from .gateway import ( - CreateGatewayRequest, - DeleteGatewayRequest, - Gateway, - GetGatewayRequest, - ListGatewaysRequest, - ListGatewaysResponse, - UpdateGatewayRequest, -) -from .grpc_route import ( - CreateGrpcRouteRequest, - DeleteGrpcRouteRequest, - GetGrpcRouteRequest, - GrpcRoute, - ListGrpcRoutesRequest, - ListGrpcRoutesResponse, - UpdateGrpcRouteRequest, -) -from .http_route import ( - CreateHttpRouteRequest, - DeleteHttpRouteRequest, - GetHttpRouteRequest, - HttpRoute, - ListHttpRoutesRequest, - ListHttpRoutesResponse, - UpdateHttpRouteRequest, -) -from .mesh import ( - CreateMeshRequest, - DeleteMeshRequest, - GetMeshRequest, - ListMeshesRequest, - ListMeshesResponse, - Mesh, - UpdateMeshRequest, -) -from .service_binding import ( - CreateServiceBindingRequest, - DeleteServiceBindingRequest, - GetServiceBindingRequest, - ListServiceBindingsRequest, - ListServiceBindingsResponse, - ServiceBinding, -) -from .tcp_route import ( - CreateTcpRouteRequest, - DeleteTcpRouteRequest, - GetTcpRouteRequest, - ListTcpRoutesRequest, - ListTcpRoutesResponse, - TcpRoute, - UpdateTcpRouteRequest, -) -from .tls_route import ( - CreateTlsRouteRequest, - DeleteTlsRouteRequest, - GetTlsRouteRequest, - ListTlsRoutesRequest, - ListTlsRoutesResponse, - TlsRoute, - UpdateTlsRouteRequest, -) - -__all__ = ( - 'EndpointMatcher', - 'OperationMetadata', - 'TrafficPortSelector', - 'CreateLbRouteExtensionRequest', - 'CreateLbTrafficExtensionRequest', - 'DeleteLbRouteExtensionRequest', - 'DeleteLbTrafficExtensionRequest', - 'ExtensionChain', - 'GetLbRouteExtensionRequest', - 'GetLbTrafficExtensionRequest', - 'LbRouteExtension', - 'LbTrafficExtension', - 'ListLbRouteExtensionsRequest', - 'ListLbRouteExtensionsResponse', - 'ListLbTrafficExtensionsRequest', - 'ListLbTrafficExtensionsResponse', - 'UpdateLbRouteExtensionRequest', - 'UpdateLbTrafficExtensionRequest', - 'EventType', - 'LoadBalancingScheme', - 'CreateEndpointPolicyRequest', - 'DeleteEndpointPolicyRequest', - 'EndpointPolicy', - 'GetEndpointPolicyRequest', - 'ListEndpointPoliciesRequest', - 'ListEndpointPoliciesResponse', - 'UpdateEndpointPolicyRequest', - 'CreateGatewayRequest', - 'DeleteGatewayRequest', - 'Gateway', - 'GetGatewayRequest', - 'ListGatewaysRequest', - 'ListGatewaysResponse', - 'UpdateGatewayRequest', - 'CreateGrpcRouteRequest', - 'DeleteGrpcRouteRequest', - 'GetGrpcRouteRequest', - 'GrpcRoute', - 'ListGrpcRoutesRequest', - 'ListGrpcRoutesResponse', - 'UpdateGrpcRouteRequest', - 'CreateHttpRouteRequest', - 'DeleteHttpRouteRequest', - 'GetHttpRouteRequest', - 'HttpRoute', - 'ListHttpRoutesRequest', - 'ListHttpRoutesResponse', - 'UpdateHttpRouteRequest', - 'CreateMeshRequest', - 'DeleteMeshRequest', - 'GetMeshRequest', - 'ListMeshesRequest', - 'ListMeshesResponse', - 'Mesh', - 'UpdateMeshRequest', - 'CreateServiceBindingRequest', - 'DeleteServiceBindingRequest', - 'GetServiceBindingRequest', - 'ListServiceBindingsRequest', - 'ListServiceBindingsResponse', - 'ServiceBinding', - 'CreateTcpRouteRequest', - 'DeleteTcpRouteRequest', - 'GetTcpRouteRequest', - 'ListTcpRoutesRequest', - 'ListTcpRoutesResponse', - 'TcpRoute', - 'UpdateTcpRouteRequest', - 'CreateTlsRouteRequest', - 'DeleteTlsRouteRequest', - 'GetTlsRouteRequest', - 'ListTlsRoutesRequest', - 'ListTlsRoutesResponse', - 'TlsRoute', - 'UpdateTlsRouteRequest', -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py deleted file mode 100644 index 0da5791569fc..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/common.py +++ /dev/null @@ -1,227 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'OperationMetadata', - 'TrafficPortSelector', - 'EndpointMatcher', - }, -) - - -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, - ) - - -class TrafficPortSelector(proto.Message): - r"""Specification of a port-based selector. - - Attributes: - ports (MutableSequence[str]): - Optional. A list of ports. Can be port numbers or port range - (example, [80-90] specifies all ports from 80 to 90, - including 80 and 90) or named ports or \* to specify all - ports. If the list is empty, all ports are selected. - """ - - ports: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class EndpointMatcher(proto.Message): - r"""A definition of a matcher that selects endpoints to which the - policies should be applied. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - metadata_label_matcher (google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher): - The matcher is based on node metadata - presented by xDS clients. - - This field is a member of `oneof`_ ``matcher_type``. - """ - - class MetadataLabelMatcher(proto.Message): - r"""The matcher that is based on node metadata presented by xDS - clients. - - Attributes: - metadata_label_match_criteria (google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria): - Specifies how matching should be done. - - Supported values are: MATCH_ANY: At least one of the Labels - specified in the matcher should match the metadata presented - by xDS client. MATCH_ALL: The metadata presented by the xDS - client should contain all of the labels specified here. - - The selection is determined based on the best match. For - example, suppose there are three EndpointPolicy resources - P1, P2 and P3 and if P1 has a the matcher as MATCH_ANY , P2 has MATCH_ALL , and P3 has MATCH_ALL - . - - If a client with label connects, the config from P1 - will be selected. - - If a client with label connects, the config from - P2 will be selected. - - If a client with label connects, the config - from P3 will be selected. - - If there is more than one best match, (for example, if a - config P4 with selector exists and if a client - with label connects), an error will be thrown. - metadata_labels (MutableSequence[google.cloud.network_services_v1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabels]): - The list of label value pairs that must match labels in the - provided metadata based on filterMatchCriteria This list can - have at most 64 entries. The list can be empty if the match - criteria is MATCH_ANY, to specify a wildcard match (i.e this - matches any client). - """ - class MetadataLabelMatchCriteria(proto.Enum): - r"""Possible criteria values that define logic of how matching is - made. - - Values: - METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED (0): - Default value. Should not be used. - MATCH_ANY (1): - At least one of the Labels specified in the - matcher should match the metadata presented by - xDS client. - MATCH_ALL (2): - The metadata presented by the xDS client - should contain all of the labels specified here. - """ - METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED = 0 - MATCH_ANY = 1 - MATCH_ALL = 2 - - class MetadataLabels(proto.Message): - r"""Defines a name-pair value for a single label. - - Attributes: - label_name (str): - Required. Label name presented as key in xDS - Node Metadata. - label_value (str): - Required. Label value presented as value - corresponding to the above key, in xDS Node - Metadata. - """ - - label_name: str = proto.Field( - proto.STRING, - number=1, - ) - label_value: str = proto.Field( - proto.STRING, - number=2, - ) - - metadata_label_match_criteria: 'EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria' = proto.Field( - proto.ENUM, - number=1, - enum='EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria', - ) - metadata_labels: MutableSequence['EndpointMatcher.MetadataLabelMatcher.MetadataLabels'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EndpointMatcher.MetadataLabelMatcher.MetadataLabels', - ) - - metadata_label_matcher: MetadataLabelMatcher = proto.Field( - proto.MESSAGE, - number=1, - oneof='matcher_type', - message=MetadataLabelMatcher, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py deleted file mode 100644 index f505dd913257..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/dep.py +++ /dev/null @@ -1,945 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkservices.v1', - manifest={ - 'EventType', - 'LoadBalancingScheme', - 'ExtensionChain', - 'LbTrafficExtension', - 'ListLbTrafficExtensionsRequest', - 'ListLbTrafficExtensionsResponse', - 'GetLbTrafficExtensionRequest', - 'CreateLbTrafficExtensionRequest', - 'UpdateLbTrafficExtensionRequest', - 'DeleteLbTrafficExtensionRequest', - 'LbRouteExtension', - 'ListLbRouteExtensionsRequest', - 'ListLbRouteExtensionsResponse', - 'GetLbRouteExtensionRequest', - 'CreateLbRouteExtensionRequest', - 'UpdateLbRouteExtensionRequest', - 'DeleteLbRouteExtensionRequest', - }, -) - - -class EventType(proto.Enum): - r"""The part of the request or response for which the extension - is called. - - Values: - EVENT_TYPE_UNSPECIFIED (0): - Unspecified value. Do not use. - REQUEST_HEADERS (1): - If included in ``supported_events``, the extension is called - when the HTTP request headers arrive. - REQUEST_BODY (2): - If included in ``supported_events``, the extension is called - when the HTTP request body arrives. - RESPONSE_HEADERS (3): - If included in ``supported_events``, the extension is called - when the HTTP response headers arrive. - RESPONSE_BODY (4): - If included in ``supported_events``, the extension is called - when the HTTP response body arrives. - REQUEST_TRAILERS (5): - If included in ``supported_events``, the extension is called - when the HTTP request trailers arrives. - RESPONSE_TRAILERS (6): - If included in ``supported_events``, the extension is called - when the HTTP response trailers arrives. - """ - EVENT_TYPE_UNSPECIFIED = 0 - REQUEST_HEADERS = 1 - REQUEST_BODY = 2 - RESPONSE_HEADERS = 3 - RESPONSE_BODY = 4 - REQUEST_TRAILERS = 5 - RESPONSE_TRAILERS = 6 - - -class LoadBalancingScheme(proto.Enum): - r"""Load balancing schemes supported by the ``LbTrafficExtension`` - resource and ``LbRouteExtension`` resource. For more information, - refer to `Choosing a load - balancer `__. - - Values: - LOAD_BALANCING_SCHEME_UNSPECIFIED (0): - Default value. Do not use. - INTERNAL_MANAGED (1): - Signifies that this is used for Internal - HTTP(S) Load Balancing. - EXTERNAL_MANAGED (2): - Signifies that this is used for External - Managed HTTP(S) Load Balancing. - """ - LOAD_BALANCING_SCHEME_UNSPECIFIED = 0 - INTERNAL_MANAGED = 1 - EXTERNAL_MANAGED = 2 - - -class ExtensionChain(proto.Message): - r"""A single extension chain wrapper that contains the match - conditions and extensions to execute. - - Attributes: - name (str): - Required. The name for this extension chain. - The name is logged as part of the HTTP request - logs. The name must conform with RFC-1034, is - restricted to lower-cased letters, numbers and - hyphens, and can have a maximum length of 63 - characters. Additionally, the first character - must be a letter and the last a letter or a - number. - match_condition (google.cloud.network_services_v1.types.ExtensionChain.MatchCondition): - Required. Conditions under which this chain - is invoked for a request. - extensions (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain.Extension]): - Required. A set of extensions to execute for the matching - request. At least one extension is required. Up to 3 - extensions can be defined for each extension chain for - ``LbTrafficExtension`` resource. ``LbRouteExtension`` chains - are limited to 1 extension per extension chain. - """ - - class MatchCondition(proto.Message): - r"""Conditions under which this chain is invoked for a request. - - Attributes: - cel_expression (str): - Required. A Common Expression Language (CEL) expression that - is used to match requests for which the extension chain is - executed. - - For more information, see `CEL matcher language - reference `__. - """ - - cel_expression: str = proto.Field( - proto.STRING, - number=1, - ) - - class Extension(proto.Message): - r"""A single extension in the chain to execute for the matching - request. - - Attributes: - name (str): - Required. The name for this extension. - The name is logged as part of the HTTP request - logs. The name must conform with RFC-1034, is - restricted to lower-cased letters, numbers and - hyphens, and can have a maximum length of 63 - characters. Additionally, the first character - must be a letter and the last a letter or a - number. - authority (str): - Optional. The ``:authority`` header in the gRPC request sent - from Envoy to the extension service. Required for Callout - extensions. - service (str): - Required. The reference to the service that runs the - extension. - - Currently only callout extensions are supported here. - - To configure a callout extension, ``service`` must be a - fully-qualified reference to a `backend - service `__ - in the format: - ``https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/backendServices/{backendService}`` - or - ``https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}``. - supported_events (MutableSequence[google.cloud.network_services_v1.types.EventType]): - Optional. A set of events during request or response - processing for which this extension is called. This field is - required for the ``LbTrafficExtension`` resource. It must - not be set for the ``LbRouteExtension`` resource. - timeout (google.protobuf.duration_pb2.Duration): - Optional. Specifies the timeout for each - individual message on the stream. The timeout - must be between 10-1000 milliseconds. Required - for Callout extensions. - fail_open (bool): - Optional. Determines how the proxy behaves if the call to - the extension fails or times out. - - When set to ``TRUE``, request or response processing - continues without error. Any subsequent extensions in the - extension chain are also executed. When set to ``FALSE`` or - the default setting of ``FALSE`` is used, one of the - following happens: - - - If response headers have not been delivered to the - downstream client, a generic 500 error is returned to the - client. The error response can be tailored by configuring - a custom error response in the load balancer. - - - If response headers have been delivered, then the HTTP - stream to the downstream client is reset. - forward_headers (MutableSequence[str]): - Optional. List of the HTTP headers to forward - to the extension (from the client or backend). - If omitted, all headers are sent. Each element - is a string indicating the header name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - authority: str = proto.Field( - proto.STRING, - number=2, - ) - service: str = proto.Field( - proto.STRING, - number=3, - ) - supported_events: MutableSequence['EventType'] = proto.RepeatedField( - proto.ENUM, - number=4, - enum='EventType', - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - fail_open: bool = proto.Field( - proto.BOOL, - number=6, - ) - forward_headers: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - match_condition: MatchCondition = proto.Field( - proto.MESSAGE, - number=2, - message=MatchCondition, - ) - extensions: MutableSequence[Extension] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Extension, - ) - - -class LbTrafficExtension(proto.Message): - r"""``LbTrafficExtension`` is a resource that lets the extension service - modify the headers and payloads of both requests and responses - without impacting the choice of backend services or any other - security policies associated with the backend service. - - Attributes: - name (str): - Required. Identifier. Name of the ``LbTrafficExtension`` - resource in the following format: - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - 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. - description (str): - Optional. A human-readable description of the - resource. - labels (MutableMapping[str, str]): - Optional. Set of labels associated with the - ``LbTrafficExtension`` resource. - - The format must comply with `the requirements for - labels `__ - for Google Cloud resources. - forwarding_rules (MutableSequence[str]): - Required. A list of references to the forwarding rules to - which this service extension is attached to. At least one - forwarding rule is required. There can be only one - ``LBTrafficExtension`` resource per forwarding rule. - extension_chains (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain]): - Required. A set of ordered extension chains - that contain the match conditions and extensions - to execute. Match conditions for each extension - chain are evaluated in sequence for a given - request. The first extension chain that has a - condition that matches the request is executed. - Any subsequent extension chains do not execute. - Limited to 5 extension chains per resource. - load_balancing_scheme (google.cloud.network_services_v1.types.LoadBalancingScheme): - Required. All backend services and forwarding rules - referenced by this extension must share the same load - balancing scheme. Supported values: ``INTERNAL_MANAGED``, - ``EXTERNAL_MANAGED``. For more information, refer to - `Choosing a load - balancer `__. - metadata (google.protobuf.struct_pb2.Struct): - Optional. The metadata provided here is included in the - ``ProcessingRequest.metadata_context.filter_metadata`` map - field. The metadata is available under the key - ``com.google.lb_traffic_extension.``. The - following variables are supported in the metadata: - - ``{forwarding_rule_id}`` - substituted with the forwarding - rule's fully qualified resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - description: str = proto.Field( - proto.STRING, - number=9, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - forwarding_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - extension_chains: MutableSequence['ExtensionChain'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ExtensionChain', - ) - load_balancing_scheme: 'LoadBalancingScheme' = proto.Field( - proto.ENUM, - number=8, - enum='LoadBalancingScheme', - ) - metadata: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=10, - message=struct_pb2.Struct, - ) - - -class ListLbTrafficExtensionsRequest(proto.Message): - r"""Message for requesting list of ``LbTrafficExtension`` resources. - - Attributes: - parent (str): - Required. The project and location from which the - ``LbTrafficExtension`` resources are listed, specified in - the following format: - ``projects/{project}/locations/{location}``. - page_size (int): - Optional. Requested page size. The server - might return fewer items than requested. If - unspecified, the server picks an appropriate - default. - page_token (str): - Optional. A token identifying a page of - results that the server returns. - filter (str): - Optional. Filtering results. - order_by (str): - Optional. Hint for how to order the results. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListLbTrafficExtensionsResponse(proto.Message): - r"""Message for response to listing ``LbTrafficExtension`` resources. - - Attributes: - lb_traffic_extensions (MutableSequence[google.cloud.network_services_v1.types.LbTrafficExtension]): - The list of ``LbTrafficExtension`` resources. - next_page_token (str): - A token identifying a page of results that - the server returns. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - lb_traffic_extensions: MutableSequence['LbTrafficExtension'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LbTrafficExtension', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetLbTrafficExtensionRequest(proto.Message): - r"""Message for getting a ``LbTrafficExtension`` resource. - - Attributes: - name (str): - Required. A name of the ``LbTrafficExtension`` resource to - get. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateLbTrafficExtensionRequest(proto.Message): - r"""Message for creating a ``LbTrafficExtension`` resource. - - Attributes: - parent (str): - Required. The parent resource of the ``LbTrafficExtension`` - resource. Must be in the format - ``projects/{project}/locations/{location}``. - lb_traffic_extension_id (str): - Required. User-provided ID of the ``LbTrafficExtension`` - resource to be created. - lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): - Required. ``LbTrafficExtension`` 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 can - ignore the request if it has already been - completed. The server guarantees 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, ignores 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, - ) - lb_traffic_extension_id: str = proto.Field( - proto.STRING, - number=2, - ) - lb_traffic_extension: 'LbTrafficExtension' = proto.Field( - proto.MESSAGE, - number=3, - message='LbTrafficExtension', - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateLbTrafficExtensionRequest(proto.Message): - r"""Message for updating a ``LbTrafficExtension`` resource. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Used to specify the fields to be overwritten in - the ``LbTrafficExtension`` resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field is overwritten if it - is in the mask. If the user does not specify a mask, then - all fields are overwritten. - lb_traffic_extension (google.cloud.network_services_v1.types.LbTrafficExtension): - Required. ``LbTrafficExtension`` resource being updated. - 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 can - ignore the request if it has already been - completed. The server guarantees 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, ignores 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, - ) - lb_traffic_extension: 'LbTrafficExtension' = proto.Field( - proto.MESSAGE, - number=2, - message='LbTrafficExtension', - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteLbTrafficExtensionRequest(proto.Message): - r"""Message for deleting a ``LbTrafficExtension`` resource. - - Attributes: - name (str): - Required. The name of the ``LbTrafficExtension`` resource to - delete. Must be in the format - ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. - 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 can - ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after 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, ignores 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 LbRouteExtension(proto.Message): - r"""``LbRouteExtension`` is a resource that lets you control where - traffic is routed to for a given request. - - Attributes: - name (str): - Required. Identifier. Name of the ``LbRouteExtension`` - resource in the following format: - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - 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. - description (str): - Optional. A human-readable description of the - resource. - labels (MutableMapping[str, str]): - Optional. Set of labels associated with the - ``LbRouteExtension`` resource. - - The format must comply with `the requirements for - labels `__ - for Google Cloud resources. - forwarding_rules (MutableSequence[str]): - Required. A list of references to the forwarding rules to - which this service extension is attached to. At least one - forwarding rule is required. There can be only one - ``LbRouteExtension`` resource per forwarding rule. - extension_chains (MutableSequence[google.cloud.network_services_v1.types.ExtensionChain]): - Required. A set of ordered extension chains - that contain the match conditions and extensions - to execute. Match conditions for each extension - chain are evaluated in sequence for a given - request. The first extension chain that has a - condition that matches the request is executed. - Any subsequent extension chains do not execute. - Limited to 5 extension chains per resource. - load_balancing_scheme (google.cloud.network_services_v1.types.LoadBalancingScheme): - Required. All backend services and forwarding rules - referenced by this extension must share the same load - balancing scheme. Supported values: ``INTERNAL_MANAGED``, - ``EXTERNAL_MANAGED``. For more information, refer to - `Choosing a load - balancer `__. - metadata (google.protobuf.struct_pb2.Struct): - Optional. The metadata provided here is included as part of - the ``metadata_context`` (of type - ``google.protobuf.Struct``) in the ``ProcessingRequest`` - message sent to the extension server. The metadata is - available under the namespace - ``com.google.lb_route_extension.``. The - following variables are supported in the metadata Struct: - - ``{forwarding_rule_id}`` - substituted with the forwarding - rule's fully qualified resource name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - description: str = proto.Field( - proto.STRING, - number=9, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - forwarding_rules: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - extension_chains: MutableSequence['ExtensionChain'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ExtensionChain', - ) - load_balancing_scheme: 'LoadBalancingScheme' = proto.Field( - proto.ENUM, - number=8, - enum='LoadBalancingScheme', - ) - metadata: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=10, - message=struct_pb2.Struct, - ) - - -class ListLbRouteExtensionsRequest(proto.Message): - r"""Message for requesting list of ``LbRouteExtension`` resources. - - Attributes: - parent (str): - Required. The project and location from which the - ``LbRouteExtension`` resources are listed, specified in the - following format: - ``projects/{project}/locations/{location}``. - page_size (int): - Optional. Requested page size. The server - might return fewer items than requested. If - unspecified, the server picks an appropriate - default. - page_token (str): - Optional. A token identifying a page of - results that the server returns. - filter (str): - Optional. Filtering results. - order_by (str): - Optional. Hint for how to order the results. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListLbRouteExtensionsResponse(proto.Message): - r"""Message for response to listing ``LbRouteExtension`` resources. - - Attributes: - lb_route_extensions (MutableSequence[google.cloud.network_services_v1.types.LbRouteExtension]): - The list of ``LbRouteExtension`` resources. - next_page_token (str): - A token identifying a page of results that - the server returns. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - lb_route_extensions: MutableSequence['LbRouteExtension'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LbRouteExtension', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetLbRouteExtensionRequest(proto.Message): - r"""Message for getting a ``LbRouteExtension`` resource. - - Attributes: - name (str): - Required. A name of the ``LbRouteExtension`` resource to - get. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateLbRouteExtensionRequest(proto.Message): - r"""Message for creating a ``LbRouteExtension`` resource. - - Attributes: - parent (str): - Required. The parent resource of the ``LbRouteExtension`` - resource. Must be in the format - ``projects/{project}/locations/{location}``. - lb_route_extension_id (str): - Required. User-provided ID of the ``LbRouteExtension`` - resource to be created. - lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): - Required. ``LbRouteExtension`` 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 can - ignore the request if it has already been - completed. The server guarantees 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, ignores 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, - ) - lb_route_extension_id: str = proto.Field( - proto.STRING, - number=2, - ) - lb_route_extension: 'LbRouteExtension' = proto.Field( - proto.MESSAGE, - number=3, - message='LbRouteExtension', - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateLbRouteExtensionRequest(proto.Message): - r"""Message for updating a ``LbRouteExtension`` resource. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Used to specify the fields to be overwritten in - the ``LbRouteExtension`` resource by the update. The fields - specified in the update_mask are relative to the resource, - not the full request. A field is overwritten if it is in the - mask. If the user does not specify a mask, then all fields - are overwritten. - lb_route_extension (google.cloud.network_services_v1.types.LbRouteExtension): - Required. ``LbRouteExtension`` resource being updated. - 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 can - ignore the request if it has already been - completed. The server guarantees 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, ignores 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, - ) - lb_route_extension: 'LbRouteExtension' = proto.Field( - proto.MESSAGE, - number=2, - message='LbRouteExtension', - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteLbRouteExtensionRequest(proto.Message): - r"""Message for deleting a ``LbRouteExtension`` resource. - - Attributes: - name (str): - Required. The name of the ``LbRouteExtension`` resource to - delete. Must be in the format - ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. - 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 can - ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after 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, ignores 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, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py deleted file mode 100644 index ee5afc6ec6ca..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/endpoint_policy.py +++ /dev/null @@ -1,317 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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_services_v1.types import common -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networkservices.v1', - manifest={ - 'EndpointPolicy', - 'ListEndpointPoliciesRequest', - 'ListEndpointPoliciesResponse', - 'GetEndpointPolicyRequest', - 'CreateEndpointPolicyRequest', - 'UpdateEndpointPolicyRequest', - 'DeleteEndpointPolicyRequest', - }, -) - - -class EndpointPolicy(proto.Message): - r"""EndpointPolicy is a resource that helps apply desired - configuration on the endpoints that match specific criteria. For - example, this resource can be used to apply "authentication - config" an all endpoints that serve on port 8080. - - Attributes: - name (str): - Required. Name of the EndpointPolicy resource. It matches - pattern - ``projects/{project}/locations/global/endpointPolicies/{endpoint_policy}``. - 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 EndpointPolicy resource. - type_ (google.cloud.network_services_v1.types.EndpointPolicy.EndpointPolicyType): - Required. The type of endpoint policy. This - is primarily used to validate the configuration. - authorization_policy (str): - Optional. This field specifies the URL of - AuthorizationPolicy resource that applies - authorization policies to the inbound traffic at - the matched endpoints. Refer to Authorization. - If this field is not specified, authorization is - disabled(no authz checks) for this endpoint. - endpoint_matcher (google.cloud.network_services_v1.types.EndpointMatcher): - Required. A matcher that selects endpoints to - which the policies should be applied. - traffic_port_selector (google.cloud.network_services_v1.types.TrafficPortSelector): - Optional. Port selector for the (matched) - endpoints. If no port selector is provided, the - matched config is applied to all ports. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - server_tls_policy (str): - Optional. A URL referring to ServerTlsPolicy - resource. ServerTlsPolicy is used to determine - the authentication policy to be applied to - terminate the inbound traffic at the identified - backends. If this field is not set, - authentication is disabled(open) for this - endpoint. - client_tls_policy (str): - Optional. A URL referring to a ClientTlsPolicy resource. - ClientTlsPolicy can be set to specify the authentication for - traffic from the proxy to the actual endpoints. More - specifically, it is applied to the outgoing traffic from the - proxy to the endpoint. This is typically used for sidecar - model where the proxy identifies itself as endpoint to the - control plane, with the connection between sidecar and - endpoint requiring authentication. If this field is not set, - authentication is disabled(open). Applicable only when - EndpointPolicyType is SIDECAR_PROXY. - """ - class EndpointPolicyType(proto.Enum): - r"""The type of endpoint policy. - - Values: - ENDPOINT_POLICY_TYPE_UNSPECIFIED (0): - Default value. Must not be used. - SIDECAR_PROXY (1): - Represents a proxy deployed as a sidecar. - GRPC_SERVER (2): - Represents a proxyless gRPC backend. - """ - ENDPOINT_POLICY_TYPE_UNSPECIFIED = 0 - SIDECAR_PROXY = 1 - GRPC_SERVER = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - type_: EndpointPolicyType = proto.Field( - proto.ENUM, - number=5, - enum=EndpointPolicyType, - ) - authorization_policy: str = proto.Field( - proto.STRING, - number=7, - ) - endpoint_matcher: common.EndpointMatcher = proto.Field( - proto.MESSAGE, - number=9, - message=common.EndpointMatcher, - ) - traffic_port_selector: common.TrafficPortSelector = proto.Field( - proto.MESSAGE, - number=10, - message=common.TrafficPortSelector, - ) - description: str = proto.Field( - proto.STRING, - number=11, - ) - server_tls_policy: str = proto.Field( - proto.STRING, - number=12, - ) - client_tls_policy: str = proto.Field( - proto.STRING, - number=13, - ) - - -class ListEndpointPoliciesRequest(proto.Message): - r"""Request used with the ListEndpointPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - EndpointPolicies should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of EndpointPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListEndpointPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListEndpointPolicies`` 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 ListEndpointPoliciesResponse(proto.Message): - r"""Response returned by the ListEndpointPolicies method. - - Attributes: - endpoint_policies (MutableSequence[google.cloud.network_services_v1.types.EndpointPolicy]): - List of EndpointPolicy 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 - - endpoint_policies: MutableSequence['EndpointPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EndpointPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEndpointPolicyRequest(proto.Message): - r"""Request used with the GetEndpointPolicy method. - - Attributes: - name (str): - Required. A name of the EndpointPolicy to get. Must be in - the format - ``projects/*/locations/global/endpointPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEndpointPolicyRequest(proto.Message): - r"""Request used with the CreateEndpointPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the EndpointPolicy. Must be - in the format ``projects/*/locations/global``. - endpoint_policy_id (str): - Required. Short name of the EndpointPolicy - resource to be created. E.g. "CustomECS". - endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): - Required. EndpointPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - endpoint_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - endpoint_policy: 'EndpointPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='EndpointPolicy', - ) - - -class UpdateEndpointPolicyRequest(proto.Message): - r"""Request used with the UpdateEndpointPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the EndpointPolicy 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. - endpoint_policy (google.cloud.network_services_v1.types.EndpointPolicy): - Required. Updated EndpointPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - endpoint_policy: 'EndpointPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='EndpointPolicy', - ) - - -class DeleteEndpointPolicyRequest(proto.Message): - r"""Request used with the DeleteEndpointPolicy method. - - Attributes: - name (str): - Required. A name of the EndpointPolicy to delete. Must be in - the format - ``projects/*/locations/global/endpointPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py deleted file mode 100644 index 8a9f0fb05e9e..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/gateway.py +++ /dev/null @@ -1,305 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'Gateway', - 'ListGatewaysRequest', - 'ListGatewaysResponse', - 'GetGatewayRequest', - 'CreateGatewayRequest', - 'UpdateGatewayRequest', - 'DeleteGatewayRequest', - }, -) - - -class Gateway(proto.Message): - r"""Gateway represents the configuration for a proxy, typically a - load balancer. It captures the ip:port over which the services - are exposed by the proxy, along with any policy configurations. - Routes have reference to to Gateways to dictate how requests - should be routed by this Gateway. - - Attributes: - name (str): - Required. Name of the Gateway resource. It matches pattern - ``projects/*/locations/*/gateways/``. - self_link (str): - Output only. Server-defined URL of this - 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 Gateway resource. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - type_ (google.cloud.network_services_v1.types.Gateway.Type): - Immutable. The type of the customer managed - gateway. This field is required. If unspecified, - an error is returned. - ports (MutableSequence[int]): - Required. One or more ports that the Gateway - must receive traffic on. The proxy binds to the - ports specified. Gateway listen on 0.0.0.0 on - the ports specified below. - scope (str): - Required. Immutable. Scope determines how - configuration across multiple Gateway instances - are merged. The configuration for multiple - Gateway instances with the same scope will be - merged as presented as a single coniguration to - the proxy/load balancer. - - Max length 64 characters. - Scope should start with a letter and can only - have letters, numbers, hyphens. - server_tls_policy (str): - Optional. A fully-qualified ServerTLSPolicy - URL reference. Specifies how TLS traffic is - terminated. If empty, TLS termination is - disabled. - """ - class Type(proto.Enum): - r"""The type of the customer-managed gateway. Possible values are: - - - OPEN_MESH - - SECURE_WEB_GATEWAY - - Values: - TYPE_UNSPECIFIED (0): - The type of the customer managed gateway is - unspecified. - OPEN_MESH (1): - The type of the customer managed gateway is - TrafficDirector Open Mesh. - SECURE_WEB_GATEWAY (2): - The type of the customer managed gateway is - SecureWebGateway (SWG). - """ - TYPE_UNSPECIFIED = 0 - OPEN_MESH = 1 - SECURE_WEB_GATEWAY = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=13, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - type_: Type = proto.Field( - proto.ENUM, - number=6, - enum=Type, - ) - ports: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=11, - ) - scope: str = proto.Field( - proto.STRING, - number=8, - ) - server_tls_policy: str = proto.Field( - proto.STRING, - number=9, - ) - - -class ListGatewaysRequest(proto.Message): - r"""Request used with the ListGateways method. - - Attributes: - parent (str): - Required. The project and location from which the Gateways - should be listed, specified in the format - ``projects/*/locations/*``. - page_size (int): - Maximum number of Gateways to return per - call. - page_token (str): - The value returned by the last ``ListGatewaysResponse`` - Indicates that this is a continuation of a prior - ``ListGateways`` 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 ListGatewaysResponse(proto.Message): - r"""Response returned by the ListGateways method. - - Attributes: - gateways (MutableSequence[google.cloud.network_services_v1.types.Gateway]): - List of Gateway 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 - - gateways: MutableSequence['Gateway'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Gateway', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetGatewayRequest(proto.Message): - r"""Request used by the GetGateway method. - - Attributes: - name (str): - Required. A name of the Gateway to get. Must be in the - format ``projects/*/locations/*/gateways/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateGatewayRequest(proto.Message): - r"""Request used by the CreateGateway method. - - Attributes: - parent (str): - Required. The parent resource of the Gateway. Must be in the - format ``projects/*/locations/*``. - gateway_id (str): - Required. Short name of the Gateway resource - to be created. - gateway (google.cloud.network_services_v1.types.Gateway): - Required. Gateway resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gateway_id: str = proto.Field( - proto.STRING, - number=2, - ) - gateway: 'Gateway' = proto.Field( - proto.MESSAGE, - number=3, - message='Gateway', - ) - - -class UpdateGatewayRequest(proto.Message): - r"""Request used by the UpdateGateway method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the Gateway 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. - gateway (google.cloud.network_services_v1.types.Gateway): - Required. Updated Gateway resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - gateway: 'Gateway' = proto.Field( - proto.MESSAGE, - number=2, - message='Gateway', - ) - - -class DeleteGatewayRequest(proto.Message): - r"""Request used by the DeleteGateway method. - - Attributes: - name (str): - Required. A name of the Gateway to delete. Must be in the - format ``projects/*/locations/*/gateways/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py deleted file mode 100644 index 1c56faba95b2..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/grpc_route.py +++ /dev/null @@ -1,719 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # 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.networkservices.v1', - manifest={ - 'GrpcRoute', - 'ListGrpcRoutesRequest', - 'ListGrpcRoutesResponse', - 'GetGrpcRouteRequest', - 'CreateGrpcRouteRequest', - 'UpdateGrpcRouteRequest', - 'DeleteGrpcRouteRequest', - }, -) - - -class GrpcRoute(proto.Message): - r"""GrpcRoute is the resource defining how gRPC traffic routed by - a Mesh or Gateway resource is routed. - - Attributes: - name (str): - Required. Name of the GrpcRoute resource. It matches pattern - ``projects/*/locations/global/grpcRoutes/`` - self_link (str): - Output only. Server-defined URL of this - 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 GrpcRoute resource. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - hostnames (MutableSequence[str]): - Required. Service hostnames with an optional port for which - this route describes traffic. - - Format: [:] - - Hostname is the fully qualified domain name of a network - host. This matches the RFC 1123 definition of a hostname - with 2 notable exceptions: - - - IPs are not allowed. - - A hostname may be prefixed with a wildcard label - (``*.``). The wildcard label must appear by itself as the - first label. - - Hostname can be "precise" which is a domain name without the - terminating dot of a network host (e.g. ``foo.example.com``) - or "wildcard", which is a domain name prefixed with a single - wildcard label (e.g. ``*.example.com``). - - Note that as per RFC1035 and RFC1123, a label must consist - of lower case alphanumeric characters or '-', and must start - and end with an alphanumeric character. No other punctuation - is allowed. - - The routes associated with a Mesh or Gateway must have - unique hostnames. If you attempt to attach multiple routes - with conflicting hostnames, the configuration will be - rejected. - - For example, while it is acceptable for routes for the - hostnames ``*.foo.bar.com`` and ``*.bar.com`` to be - associated with the same route, it is not possible to - associate two routes both with ``*.bar.com`` or both with - ``bar.com``. - - If a port is specified, then gRPC clients must use the - channel URI with the port to match this rule (i.e. - "xds:///service:123"), otherwise they must supply the URI - without a port (i.e. "xds:///service"). - meshes (MutableSequence[str]): - Optional. Meshes defines a list of meshes this GrpcRoute is - attached to, as one of the routing rules to route the - requests served by the mesh. - - Each mesh reference should match the pattern: - ``projects/*/locations/global/meshes/`` - gateways (MutableSequence[str]): - Optional. Gateways defines a list of gateways this GrpcRoute - is attached to, as one of the routing rules to route the - requests served by the gateway. - - Each gateway reference should match the pattern: - ``projects/*/locations/global/gateways/`` - rules (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.RouteRule]): - Required. A list of detailed rules defining - how to route traffic. - Within a single GrpcRoute, the - GrpcRoute.RouteAction associated with the first - matching GrpcRoute.RouteRule will be executed. - At least one rule must be supplied. - """ - - class MethodMatch(proto.Message): - r"""Specifies a match against a method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.cloud.network_services_v1.types.GrpcRoute.MethodMatch.Type): - Optional. Specifies how to match against the - name. If not specified, a default value of - "EXACT" is used. - grpc_service (str): - Required. Name of the service to match - against. If unspecified, will match all - services. - grpc_method (str): - Required. Name of the method to match - against. If unspecified, will match all methods. - case_sensitive (bool): - Optional. Specifies that matches are case sensitive. The - default value is true. case_sensitive must not be used with - a type of REGULAR_EXPRESSION. - - This field is a member of `oneof`_ ``_case_sensitive``. - """ - class Type(proto.Enum): - r"""The type of the match. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified. - EXACT (1): - Will only match the exact name provided. - REGULAR_EXPRESSION (2): - Will interpret grpc_method and grpc_service as regexes. RE2 - syntax is supported. - """ - TYPE_UNSPECIFIED = 0 - EXACT = 1 - REGULAR_EXPRESSION = 2 - - type_: 'GrpcRoute.MethodMatch.Type' = proto.Field( - proto.ENUM, - number=1, - enum='GrpcRoute.MethodMatch.Type', - ) - grpc_service: str = proto.Field( - proto.STRING, - number=2, - ) - grpc_method: str = proto.Field( - proto.STRING, - number=3, - ) - case_sensitive: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - class HeaderMatch(proto.Message): - r"""A match against a collection of headers. - - Attributes: - type_ (google.cloud.network_services_v1.types.GrpcRoute.HeaderMatch.Type): - Optional. Specifies how to match against the - value of the header. If not specified, a default - value of EXACT is used. - key (str): - Required. The key of the header. - value (str): - Required. The value of the header. - """ - class Type(proto.Enum): - r"""The type of match. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified. - EXACT (1): - Will only match the exact value provided. - REGULAR_EXPRESSION (2): - Will match paths conforming to the prefix - specified by value. RE2 syntax is supported. - """ - TYPE_UNSPECIFIED = 0 - EXACT = 1 - REGULAR_EXPRESSION = 2 - - type_: 'GrpcRoute.HeaderMatch.Type' = proto.Field( - proto.ENUM, - number=1, - enum='GrpcRoute.HeaderMatch.Type', - ) - key: str = proto.Field( - proto.STRING, - number=2, - ) - value: str = proto.Field( - proto.STRING, - number=3, - ) - - class RouteMatch(proto.Message): - r"""Criteria for matching traffic. A RouteMatch will be - considered to match when all supplied fields match. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - method (google.cloud.network_services_v1.types.GrpcRoute.MethodMatch): - Optional. A gRPC method to match against. If - this field is empty or omitted, will match all - methods. - - This field is a member of `oneof`_ ``_method``. - headers (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.HeaderMatch]): - Optional. Specifies a collection of headers - to match. - """ - - method: 'GrpcRoute.MethodMatch' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='GrpcRoute.MethodMatch', - ) - headers: MutableSequence['GrpcRoute.HeaderMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='GrpcRoute.HeaderMatch', - ) - - class Destination(proto.Message): - r"""The destination to which traffic will be routed. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - service_name (str): - Required. The URL of a destination service to - which to route traffic. Must refer to either a - BackendService or ServiceDirectoryService. - - This field is a member of `oneof`_ ``destination_type``. - weight (int): - Optional. Specifies the proportion of - requests forwarded to the backend referenced by - the serviceName field. This is computed as: - - - weight/Sum(weights in this destination list). - For non-zero values, there may be some epsilon - from the exact proportion defined here - depending on the precision an implementation - supports. - - If only one serviceName is specified and it has - a weight greater than 0, 100% of the traffic is - forwarded to that backend. - - If weights are specified for any one service - name, they need to be specified for all of them. - - If weights are unspecified for all services, - then, traffic is distributed in equal - proportions to all of them. - - This field is a member of `oneof`_ ``_weight``. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - oneof='destination_type', - ) - weight: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - class FaultInjectionPolicy(proto.Message): - r"""The specification for fault injection introduced into traffic - to test the resiliency of clients to destination service - failure. As part of fault injection, when clients send requests - to a destination, delays can be introduced on a percentage of - requests before sending those requests to the destination - service. Similarly requests from clients can be aborted by for a - percentage of requests. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - delay (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy.Delay): - The specification for injecting delay to - client requests. - - This field is a member of `oneof`_ ``_delay``. - abort (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy.Abort): - The specification for aborting to client - requests. - - This field is a member of `oneof`_ ``_abort``. - """ - - class Delay(proto.Message): - r"""Specification of how client requests are delayed as part of - fault injection before being sent to a destination. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - fixed_delay (google.protobuf.duration_pb2.Duration): - Specify a fixed delay before forwarding the - request. - - This field is a member of `oneof`_ ``_fixed_delay``. - percentage (int): - The percentage of traffic on which delay will be injected. - - The value must be between [0, 100] - - This field is a member of `oneof`_ ``_percentage``. - """ - - fixed_delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message=duration_pb2.Duration, - ) - percentage: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - class Abort(proto.Message): - r"""Specification of how client requests are aborted as part of - fault injection before being sent to a destination. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - http_status (int): - The HTTP status code used to abort the - request. - The value must be between 200 and 599 inclusive. - - This field is a member of `oneof`_ ``_http_status``. - percentage (int): - The percentage of traffic which will be aborted. - - The value must be between [0, 100] - - This field is a member of `oneof`_ ``_percentage``. - """ - - http_status: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - percentage: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - delay: 'GrpcRoute.FaultInjectionPolicy.Delay' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='GrpcRoute.FaultInjectionPolicy.Delay', - ) - abort: 'GrpcRoute.FaultInjectionPolicy.Abort' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='GrpcRoute.FaultInjectionPolicy.Abort', - ) - - class RetryPolicy(proto.Message): - r"""The specifications for retries. - - Attributes: - retry_conditions (MutableSequence[str]): - - connect-failure: Router will retry on failures connecting - to Backend Services, for example due to connection - timeouts. - - refused-stream: Router will retry if the backend service - resets the stream with a REFUSED_STREAM error code. This - reset type indicates that it is safe to retry. - - cancelled: Router will retry if the gRPC status code in - the response header is set to cancelled - - deadline-exceeded: Router will retry if the gRPC status - code in the response header is set to deadline-exceeded - - resource-exhausted: Router will retry if the gRPC status - code in the response header is set to resource-exhausted - - unavailable: Router will retry if the gRPC status code in - the response header is set to unavailable - num_retries (int): - Specifies the allowed number of retries. This - number must be > 0. If not specified, default to - 1. - """ - - retry_conditions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - num_retries: int = proto.Field( - proto.UINT32, - number=2, - ) - - class RouteAction(proto.Message): - r"""Specifies how to route matched traffic. - - Attributes: - destinations (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.Destination]): - Optional. The destination services to which - traffic should be forwarded. If multiple - destinations are specified, traffic will be - split between Backend Service(s) according to - the weight field of these destinations. - fault_injection_policy (google.cloud.network_services_v1.types.GrpcRoute.FaultInjectionPolicy): - Optional. The specification for fault injection introduced - into traffic to test the resiliency of clients to - destination service failure. As part of fault injection, - when clients send requests to a destination, delays can be - introduced on a percentage of requests before sending those - requests to the destination service. Similarly requests from - clients can be aborted by for a percentage of requests. - - timeout and retry_policy will be ignored by clients that are - configured with a fault_injection_policy - timeout (google.protobuf.duration_pb2.Duration): - Optional. Specifies the timeout for selected - route. Timeout is computed from the time the - request has been fully processed (i.e. end of - stream) up until the response has been - completely processed. Timeout includes all - retries. - retry_policy (google.cloud.network_services_v1.types.GrpcRoute.RetryPolicy): - Optional. Specifies the retry policy - associated with this route. - """ - - destinations: MutableSequence['GrpcRoute.Destination'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GrpcRoute.Destination', - ) - fault_injection_policy: 'GrpcRoute.FaultInjectionPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='GrpcRoute.FaultInjectionPolicy', - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - retry_policy: 'GrpcRoute.RetryPolicy' = proto.Field( - proto.MESSAGE, - number=8, - message='GrpcRoute.RetryPolicy', - ) - - class RouteRule(proto.Message): - r"""Describes how to route traffic. - - Attributes: - matches (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute.RouteMatch]): - Optional. Matches define conditions used for - matching the rule against incoming gRPC - requests. Each match is independent, i.e. this - rule will be matched if ANY one of the matches - is satisfied. If no matches field is specified, - this rule will unconditionally match traffic. - action (google.cloud.network_services_v1.types.GrpcRoute.RouteAction): - Required. A detailed rule defining how to - route traffic. This field is required. - """ - - matches: MutableSequence['GrpcRoute.RouteMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GrpcRoute.RouteMatch', - ) - action: 'GrpcRoute.RouteAction' = proto.Field( - proto.MESSAGE, - number=2, - message='GrpcRoute.RouteAction', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=12, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - hostnames: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - meshes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - gateways: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - rules: MutableSequence[RouteRule] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=RouteRule, - ) - - -class ListGrpcRoutesRequest(proto.Message): - r"""Request used with the ListGrpcRoutes method. - - Attributes: - parent (str): - Required. The project and location from which the GrpcRoutes - should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of GrpcRoutes to return per - call. - page_token (str): - The value returned by the last ``ListGrpcRoutesResponse`` - Indicates that this is a continuation of a prior - ``ListGrpcRoutes`` 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 ListGrpcRoutesResponse(proto.Message): - r"""Response returned by the ListGrpcRoutes method. - - Attributes: - grpc_routes (MutableSequence[google.cloud.network_services_v1.types.GrpcRoute]): - List of GrpcRoute 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 - - grpc_routes: MutableSequence['GrpcRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GrpcRoute', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetGrpcRouteRequest(proto.Message): - r"""Request used by the GetGrpcRoute method. - - Attributes: - name (str): - Required. A name of the GrpcRoute to get. Must be in the - format ``projects/*/locations/global/grpcRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateGrpcRouteRequest(proto.Message): - r"""Request used by the CreateGrpcRoute method. - - Attributes: - parent (str): - Required. The parent resource of the GrpcRoute. Must be in - the format ``projects/*/locations/global``. - grpc_route_id (str): - Required. Short name of the GrpcRoute - resource to be created. - grpc_route (google.cloud.network_services_v1.types.GrpcRoute): - Required. GrpcRoute resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - grpc_route_id: str = proto.Field( - proto.STRING, - number=2, - ) - grpc_route: 'GrpcRoute' = proto.Field( - proto.MESSAGE, - number=3, - message='GrpcRoute', - ) - - -class UpdateGrpcRouteRequest(proto.Message): - r"""Request used by the UpdateGrpcRoute method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the GrpcRoute 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. - grpc_route (google.cloud.network_services_v1.types.GrpcRoute): - Required. Updated GrpcRoute resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - grpc_route: 'GrpcRoute' = proto.Field( - proto.MESSAGE, - number=2, - message='GrpcRoute', - ) - - -class DeleteGrpcRouteRequest(proto.Message): - r"""Request used by the DeleteGrpcRoute method. - - Attributes: - name (str): - Required. A name of the GrpcRoute to delete. Must be in the - format ``projects/*/locations/global/grpcRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py deleted file mode 100644 index 9a2314925e06..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/http_route.py +++ /dev/null @@ -1,1125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # 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.networkservices.v1', - manifest={ - 'HttpRoute', - 'ListHttpRoutesRequest', - 'ListHttpRoutesResponse', - 'GetHttpRouteRequest', - 'CreateHttpRouteRequest', - 'UpdateHttpRouteRequest', - 'DeleteHttpRouteRequest', - }, -) - - -class HttpRoute(proto.Message): - r"""HttpRoute is the resource defining how HTTP traffic should be - routed by a Mesh or Gateway resource. - - Attributes: - name (str): - Required. Name of the HttpRoute resource. It matches pattern - ``projects/*/locations/global/httpRoutes/http_route_name>``. - self_link (str): - Output only. Server-defined URL of this - resource - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - 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. - hostnames (MutableSequence[str]): - Required. Hostnames define a set of hosts that should match - against the HTTP host header to select a HttpRoute to - process the request. Hostname is the fully qualified domain - name of a network host, as defined by RFC 1123 with the - exception that: - - - IPs are not allowed. - - A hostname may be prefixed with a wildcard label - (``*.``). The wildcard label must appear by itself as the - first label. - - Hostname can be "precise" which is a domain name without the - terminating dot of a network host (e.g. ``foo.example.com``) - or "wildcard", which is a domain name prefixed with a single - wildcard label (e.g. ``*.example.com``). - - Note that as per RFC1035 and RFC1123, a label must consist - of lower case alphanumeric characters or '-', and must start - and end with an alphanumeric character. No other punctuation - is allowed. - - The routes associated with a Mesh or Gateways must have - unique hostnames. If you attempt to attach multiple routes - with conflicting hostnames, the configuration will be - rejected. - - For example, while it is acceptable for routes for the - hostnames ``*.foo.bar.com`` and ``*.bar.com`` to be - associated with the same Mesh (or Gateways under the same - scope), it is not possible to associate two routes both with - ``*.bar.com`` or both with ``bar.com``. - meshes (MutableSequence[str]): - Optional. Meshes defines a list of meshes this HttpRoute is - attached to, as one of the routing rules to route the - requests served by the mesh. - - Each mesh reference should match the pattern: - ``projects/*/locations/global/meshes/`` - - The attached Mesh should be of a type SIDECAR - gateways (MutableSequence[str]): - Optional. Gateways defines a list of gateways this HttpRoute - is attached to, as one of the routing rules to route the - requests served by the gateway. - - Each gateway reference should match the pattern: - ``projects/*/locations/global/gateways/`` - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the HttpRoute resource. - rules (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.RouteRule]): - Required. Rules that define how traffic is - routed and handled. Rules will be matched - sequentially based on the RouteMatch specified - for the rule. - """ - - class HeaderMatch(proto.Message): - r"""Specifies how to select a route rule based on HTTP request - headers. - - 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: - exact_match (str): - The value of the header should match exactly the content of - exact_match. - - This field is a member of `oneof`_ ``MatchType``. - regex_match (str): - The value of the header must match the regular expression - specified in regex_match. For regular expression grammar, - please see: https://github.com/google/re2/wiki/Syntax - - This field is a member of `oneof`_ ``MatchType``. - prefix_match (str): - The value of the header must start with the contents of - prefix_match. - - This field is a member of `oneof`_ ``MatchType``. - present_match (bool): - A header with header_name must exist. The match takes place - whether or not the header has a value. - - This field is a member of `oneof`_ ``MatchType``. - suffix_match (str): - The value of the header must end with the contents of - suffix_match. - - This field is a member of `oneof`_ ``MatchType``. - range_match (google.cloud.network_services_v1.types.HttpRoute.HeaderMatch.IntegerRange): - If specified, the rule will match if the - request header value is within the range. - - This field is a member of `oneof`_ ``MatchType``. - header (str): - The name of the HTTP header to match against. - invert_match (bool): - If specified, the match result will be - inverted before checking. Default value is set - to false. - """ - - class IntegerRange(proto.Message): - r"""Represents an integer value range. - - Attributes: - start (int): - Start of the range (inclusive) - end (int): - End of the range (exclusive) - """ - - start: int = proto.Field( - proto.INT32, - number=1, - ) - end: int = proto.Field( - proto.INT32, - number=2, - ) - - exact_match: str = proto.Field( - proto.STRING, - number=2, - oneof='MatchType', - ) - regex_match: str = proto.Field( - proto.STRING, - number=3, - oneof='MatchType', - ) - prefix_match: str = proto.Field( - proto.STRING, - number=4, - oneof='MatchType', - ) - present_match: bool = proto.Field( - proto.BOOL, - number=5, - oneof='MatchType', - ) - suffix_match: str = proto.Field( - proto.STRING, - number=6, - oneof='MatchType', - ) - range_match: 'HttpRoute.HeaderMatch.IntegerRange' = proto.Field( - proto.MESSAGE, - number=7, - oneof='MatchType', - message='HttpRoute.HeaderMatch.IntegerRange', - ) - header: str = proto.Field( - proto.STRING, - number=1, - ) - invert_match: bool = proto.Field( - proto.BOOL, - number=8, - ) - - class QueryParameterMatch(proto.Message): - r"""Specifications to match a query parameter in the request. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - exact_match (str): - The value of the query parameter must exactly match the - contents of exact_match. - - Only one of exact_match, regex_match, or present_match must - be set. - - This field is a member of `oneof`_ ``MatchType``. - regex_match (str): - The value of the query parameter must match the regular - expression specified by regex_match. For regular expression - grammar, please see - https://github.com/google/re2/wiki/Syntax - - Only one of exact_match, regex_match, or present_match must - be set. - - This field is a member of `oneof`_ ``MatchType``. - present_match (bool): - Specifies that the QueryParameterMatcher matches if request - contains query parameter, irrespective of whether the - parameter has a value or not. - - Only one of exact_match, regex_match, or present_match must - be set. - - This field is a member of `oneof`_ ``MatchType``. - query_parameter (str): - The name of the query parameter to match. - """ - - exact_match: str = proto.Field( - proto.STRING, - number=2, - oneof='MatchType', - ) - regex_match: str = proto.Field( - proto.STRING, - number=3, - oneof='MatchType', - ) - present_match: bool = proto.Field( - proto.BOOL, - number=4, - oneof='MatchType', - ) - query_parameter: str = proto.Field( - proto.STRING, - number=1, - ) - - class RouteMatch(proto.Message): - r"""RouteMatch defines specifications used to match requests. If - multiple match types are set, this RouteMatch will match if ALL - type of matches are matched. - - 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: - full_path_match (str): - The HTTP request path value should exactly match this value. - - Only one of full_path_match, prefix_match, or regex_match - should be used. - - This field is a member of `oneof`_ ``PathMatch``. - prefix_match (str): - The HTTP request path value must begin with specified - prefix_match. prefix_match must begin with a /. - - Only one of full_path_match, prefix_match, or regex_match - should be used. - - This field is a member of `oneof`_ ``PathMatch``. - regex_match (str): - The HTTP request path value must satisfy the regular - expression specified by regex_match after removing any query - parameters and anchor supplied with the original URL. For - regular expression grammar, please see - https://github.com/google/re2/wiki/Syntax - - Only one of full_path_match, prefix_match, or regex_match - should be used. - - This field is a member of `oneof`_ ``PathMatch``. - ignore_case (bool): - Specifies if prefix_match and full_path_match matches are - case sensitive. The default value is false. - headers (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.HeaderMatch]): - Specifies a list of HTTP request headers to - match against. ALL of the supplied headers must - be matched. - query_parameters (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.QueryParameterMatch]): - Specifies a list of query parameters to match - against. ALL of the query parameters must be - matched. - """ - - full_path_match: str = proto.Field( - proto.STRING, - number=1, - oneof='PathMatch', - ) - prefix_match: str = proto.Field( - proto.STRING, - number=2, - oneof='PathMatch', - ) - regex_match: str = proto.Field( - proto.STRING, - number=3, - oneof='PathMatch', - ) - ignore_case: bool = proto.Field( - proto.BOOL, - number=4, - ) - headers: MutableSequence['HttpRoute.HeaderMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='HttpRoute.HeaderMatch', - ) - query_parameters: MutableSequence['HttpRoute.QueryParameterMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='HttpRoute.QueryParameterMatch', - ) - - class Destination(proto.Message): - r"""Specifications of a destination to which the request should - be routed to. - - Attributes: - service_name (str): - The URL of a BackendService to route traffic - to. - weight (int): - Specifies the proportion of requests - forwarded to the backend referenced by the - serviceName field. This is computed as: - - - weight/Sum(weights in this destination list). - For non-zero values, there may be some epsilon - from the exact proportion defined here - depending on the precision an implementation - supports. - - If only one serviceName is specified and it has - a weight greater than 0, 100% of the traffic is - forwarded to that backend. - - If weights are specified for any one service - name, they need to be specified for all of them. - - If weights are unspecified for all services, - then, traffic is distributed in equal - proportions to all of them. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - weight: int = proto.Field( - proto.INT32, - number=2, - ) - - class Redirect(proto.Message): - r"""The specification for redirecting traffic. - - Attributes: - host_redirect (str): - The host that will be used in the redirect - response instead of the one that was supplied in - the request. - path_redirect (str): - The path that will be used in the redirect response instead - of the one that was supplied in the request. path_redirect - can not be supplied together with prefix_redirect. Supply - one alone or neither. If neither is supplied, the path of - the original request will be used for the redirect. - prefix_rewrite (str): - Indicates that during redirection, the - matched prefix (or path) should be swapped with - this value. This option allows URLs be - dynamically created based on the request. - response_code (google.cloud.network_services_v1.types.HttpRoute.Redirect.ResponseCode): - The HTTP Status code to use for the redirect. - https_redirect (bool): - If set to true, the URL scheme in the - redirected request is set to https. If set to - false, the URL scheme of the redirected request - will remain the same as that of the request. - - The default is set to false. - strip_query (bool): - if set to true, any accompanying query - portion of the original URL is removed prior to - redirecting the request. If set to false, the - query portion of the original URL is retained. - - The default is set to false. - port_redirect (int): - The port that will be used in the redirected - request instead of the one that was supplied in - the request. - """ - class ResponseCode(proto.Enum): - r"""Supported HTTP response code. - - Values: - RESPONSE_CODE_UNSPECIFIED (0): - Default value - MOVED_PERMANENTLY_DEFAULT (1): - Corresponds to 301. - FOUND (2): - Corresponds to 302. - SEE_OTHER (3): - Corresponds to 303. - TEMPORARY_REDIRECT (4): - Corresponds to 307. In this case, the request - method will be retained. - PERMANENT_REDIRECT (5): - Corresponds to 308. In this case, the request - method will be retained. - """ - RESPONSE_CODE_UNSPECIFIED = 0 - MOVED_PERMANENTLY_DEFAULT = 1 - FOUND = 2 - SEE_OTHER = 3 - TEMPORARY_REDIRECT = 4 - PERMANENT_REDIRECT = 5 - - host_redirect: str = proto.Field( - proto.STRING, - number=1, - ) - path_redirect: str = proto.Field( - proto.STRING, - number=2, - ) - prefix_rewrite: str = proto.Field( - proto.STRING, - number=3, - ) - response_code: 'HttpRoute.Redirect.ResponseCode' = proto.Field( - proto.ENUM, - number=4, - enum='HttpRoute.Redirect.ResponseCode', - ) - https_redirect: bool = proto.Field( - proto.BOOL, - number=5, - ) - strip_query: bool = proto.Field( - proto.BOOL, - number=6, - ) - port_redirect: int = proto.Field( - proto.INT32, - number=7, - ) - - class FaultInjectionPolicy(proto.Message): - r"""The specification for fault injection introduced into traffic - to test the resiliency of clients to destination service - failure. As part of fault injection, when clients send requests - to a destination, delays can be introduced by client proxy on a - percentage of requests before sending those requests to the - destination service. Similarly requests can be aborted by client - proxy for a percentage of requests. - - Attributes: - delay (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy.Delay): - The specification for injecting delay to - client requests. - abort (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy.Abort): - The specification for aborting to client - requests. - """ - - class Delay(proto.Message): - r"""Specification of how client requests are delayed as part of - fault injection before being sent to a destination. - - Attributes: - fixed_delay (google.protobuf.duration_pb2.Duration): - Specify a fixed delay before forwarding the - request. - percentage (int): - The percentage of traffic on which delay will be injected. - - The value must be between [0, 100] - """ - - fixed_delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - percentage: int = proto.Field( - proto.INT32, - number=2, - ) - - class Abort(proto.Message): - r"""Specification of how client requests are aborted as part of - fault injection before being sent to a destination. - - Attributes: - http_status (int): - The HTTP status code used to abort the - request. - The value must be between 200 and 599 inclusive. - percentage (int): - The percentage of traffic which will be aborted. - - The value must be between [0, 100] - """ - - http_status: int = proto.Field( - proto.INT32, - number=1, - ) - percentage: int = proto.Field( - proto.INT32, - number=2, - ) - - delay: 'HttpRoute.FaultInjectionPolicy.Delay' = proto.Field( - proto.MESSAGE, - number=1, - message='HttpRoute.FaultInjectionPolicy.Delay', - ) - abort: 'HttpRoute.FaultInjectionPolicy.Abort' = proto.Field( - proto.MESSAGE, - number=2, - message='HttpRoute.FaultInjectionPolicy.Abort', - ) - - class HeaderModifier(proto.Message): - r"""The specification for modifying HTTP header in HTTP request - and HTTP response. - - Attributes: - set (MutableMapping[str, str]): - Completely overwrite/replace the headers with - given map where key is the name of the header, - value is the value of the header. - add (MutableMapping[str, str]): - Add the headers with given map where key is - the name of the header, value is the value of - the header. - remove (MutableSequence[str]): - Remove headers (matching by header names) - specified in the list. - """ - - set: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - add: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - remove: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - class URLRewrite(proto.Message): - r"""The specification for modifying the URL of the request, prior - to forwarding the request to the destination. - - Attributes: - path_prefix_rewrite (str): - Prior to forwarding the request to the - selected destination, the matching portion of - the requests path is replaced by this value. - host_rewrite (str): - Prior to forwarding the request to the - selected destination, the requests host header - is replaced by this value. - """ - - path_prefix_rewrite: str = proto.Field( - proto.STRING, - number=1, - ) - host_rewrite: str = proto.Field( - proto.STRING, - number=2, - ) - - class RetryPolicy(proto.Message): - r"""The specifications for retries. - - Attributes: - retry_conditions (MutableSequence[str]): - Specifies one or more conditions when this retry policy - applies. Valid values are: 5xx: Proxy will attempt a retry - if the destination service responds with any 5xx response - code, of if the destination service does not respond at all, - example: disconnect, reset, read timeout, connection failure - and refused streams. - - gateway-error: Similar to 5xx, but only applies to response - codes 502, 503, 504. - - reset: Proxy will attempt a retry if the destination service - does not respond at all (disconnect/reset/read timeout) - - connect-failure: Proxy will retry on failures connecting to - destination for example due to connection timeouts. - - retriable-4xx: Proxy will retry fro retriable 4xx response - codes. Currently the only retriable error supported is 409. - - refused-stream: Proxy will retry if the destination resets - the stream with a REFUSED_STREAM error code. This reset type - indicates that it is safe to retry. - num_retries (int): - Specifies the allowed number of retries. This - number must be > 0. If not specified, default to - 1. - per_try_timeout (google.protobuf.duration_pb2.Duration): - Specifies a non-zero timeout per retry - attempt. - """ - - retry_conditions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - num_retries: int = proto.Field( - proto.INT32, - number=2, - ) - per_try_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - class RequestMirrorPolicy(proto.Message): - r"""Specifies the policy on how requests are shadowed to a - separate mirrored destination service. The proxy does not wait - for responses from the shadow service. Prior to sending traffic - to the shadow service, the host/authority header is suffixed - with -shadow. - - Attributes: - destination (google.cloud.network_services_v1.types.HttpRoute.Destination): - The destination the requests will be mirrored - to. The weight of the destination will be - ignored. - """ - - destination: 'HttpRoute.Destination' = proto.Field( - proto.MESSAGE, - number=1, - message='HttpRoute.Destination', - ) - - class CorsPolicy(proto.Message): - r"""The Specification for allowing client side cross-origin - requests. - - Attributes: - allow_origins (MutableSequence[str]): - Specifies the list of origins that will be allowed to do - CORS requests. An origin is allowed if it matches either an - item in allow_origins or an item in allow_origin_regexes. - allow_origin_regexes (MutableSequence[str]): - Specifies the regular expression patterns - that match allowed origins. For regular - expression grammar, please see - https://github.com/google/re2/wiki/Syntax. - allow_methods (MutableSequence[str]): - Specifies the content for - Access-Control-Allow-Methods header. - allow_headers (MutableSequence[str]): - Specifies the content for - Access-Control-Allow-Headers header. - expose_headers (MutableSequence[str]): - Specifies the content for - Access-Control-Expose-Headers header. - max_age (str): - Specifies how long result of a preflight - request can be cached in seconds. This - translates to the Access-Control-Max-Age header. - allow_credentials (bool): - In response to a preflight request, setting - this to true indicates that the actual request - can include user credentials. This translates to - the Access-Control-Allow-Credentials header. - - Default value is false. - disabled (bool): - If true, the CORS policy is disabled. The - default value is false, which indicates that the - CORS policy is in effect. - """ - - allow_origins: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - allow_origin_regexes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - allow_methods: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - allow_headers: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - expose_headers: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - max_age: str = proto.Field( - proto.STRING, - number=6, - ) - allow_credentials: bool = proto.Field( - proto.BOOL, - number=7, - ) - disabled: bool = proto.Field( - proto.BOOL, - number=8, - ) - - class RouteAction(proto.Message): - r"""The specifications for routing traffic and applying - associated policies. - - Attributes: - destinations (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.Destination]): - The destination to which traffic should be - forwarded. - redirect (google.cloud.network_services_v1.types.HttpRoute.Redirect): - If set, the request is directed as configured - by this field. - fault_injection_policy (google.cloud.network_services_v1.types.HttpRoute.FaultInjectionPolicy): - The specification for fault injection introduced into - traffic to test the resiliency of clients to backend service - failure. As part of fault injection, when clients send - requests to a backend service, delays can be introduced on a - percentage of requests before sending those requests to the - backend service. Similarly requests from clients can be - aborted for a percentage of requests. - - timeout and retry_policy will be ignored by clients that are - configured with a fault_injection_policy - request_header_modifier (google.cloud.network_services_v1.types.HttpRoute.HeaderModifier): - The specification for modifying the headers - of a matching request prior to delivery of the - request to the destination. If HeaderModifiers - are set on both the Destination and the - RouteAction, they will be merged. Conflicts - between the two will not be resolved on the - configuration. - response_header_modifier (google.cloud.network_services_v1.types.HttpRoute.HeaderModifier): - The specification for modifying the headers - of a response prior to sending the response back - to the client. If HeaderModifiers are set on - both the Destination and the RouteAction, they - will be merged. Conflicts between the two will - not be resolved on the configuration. - url_rewrite (google.cloud.network_services_v1.types.HttpRoute.URLRewrite): - The specification for rewrite URL before - forwarding requests to the destination. - timeout (google.protobuf.duration_pb2.Duration): - Specifies the timeout for selected route. - Timeout is computed from the time the request - has been fully processed (i.e. end of stream) up - until the response has been completely - processed. Timeout includes all retries. - retry_policy (google.cloud.network_services_v1.types.HttpRoute.RetryPolicy): - Specifies the retry policy associated with - this route. - request_mirror_policy (google.cloud.network_services_v1.types.HttpRoute.RequestMirrorPolicy): - Specifies the policy on how requests intended - for the routes destination are shadowed to a - separate mirrored destination. Proxy will not - wait for the shadow destination to respond - before returning the response. Prior to sending - traffic to the shadow service, the - host/authority header is suffixed with -shadow. - cors_policy (google.cloud.network_services_v1.types.HttpRoute.CorsPolicy): - The specification for allowing client side - cross-origin requests. - """ - - destinations: MutableSequence['HttpRoute.Destination'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='HttpRoute.Destination', - ) - redirect: 'HttpRoute.Redirect' = proto.Field( - proto.MESSAGE, - number=2, - message='HttpRoute.Redirect', - ) - fault_injection_policy: 'HttpRoute.FaultInjectionPolicy' = proto.Field( - proto.MESSAGE, - number=4, - message='HttpRoute.FaultInjectionPolicy', - ) - request_header_modifier: 'HttpRoute.HeaderModifier' = proto.Field( - proto.MESSAGE, - number=5, - message='HttpRoute.HeaderModifier', - ) - response_header_modifier: 'HttpRoute.HeaderModifier' = proto.Field( - proto.MESSAGE, - number=6, - message='HttpRoute.HeaderModifier', - ) - url_rewrite: 'HttpRoute.URLRewrite' = proto.Field( - proto.MESSAGE, - number=7, - message='HttpRoute.URLRewrite', - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - retry_policy: 'HttpRoute.RetryPolicy' = proto.Field( - proto.MESSAGE, - number=9, - message='HttpRoute.RetryPolicy', - ) - request_mirror_policy: 'HttpRoute.RequestMirrorPolicy' = proto.Field( - proto.MESSAGE, - number=10, - message='HttpRoute.RequestMirrorPolicy', - ) - cors_policy: 'HttpRoute.CorsPolicy' = proto.Field( - proto.MESSAGE, - number=11, - message='HttpRoute.CorsPolicy', - ) - - class RouteRule(proto.Message): - r"""Specifies how to match traffic and how to route traffic when - traffic is matched. - - Attributes: - matches (MutableSequence[google.cloud.network_services_v1.types.HttpRoute.RouteMatch]): - A list of matches define conditions used for - matching the rule against incoming HTTP - requests. Each match is independent, i.e. this - rule will be matched if ANY one of the matches - is satisfied. - - If no matches field is specified, this rule will - unconditionally match traffic. - - If a default rule is desired to be configured, - add a rule with no matches specified to the end - of the rules list. - action (google.cloud.network_services_v1.types.HttpRoute.RouteAction): - The detailed rule defining how to route - matched traffic. - """ - - matches: MutableSequence['HttpRoute.RouteMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='HttpRoute.RouteMatch', - ) - action: 'HttpRoute.RouteAction' = proto.Field( - proto.MESSAGE, - number=2, - message='HttpRoute.RouteAction', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=11, - ) - 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, - ) - hostnames: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - meshes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - gateways: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - rules: MutableSequence[RouteRule] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=RouteRule, - ) - - -class ListHttpRoutesRequest(proto.Message): - r"""Request used with the ListHttpRoutes method. - - Attributes: - parent (str): - Required. The project and location from which the HttpRoutes - should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of HttpRoutes to return per - call. - page_token (str): - The value returned by the last ``ListHttpRoutesResponse`` - Indicates that this is a continuation of a prior - ``ListHttpRoutes`` 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 ListHttpRoutesResponse(proto.Message): - r"""Response returned by the ListHttpRoutes method. - - Attributes: - http_routes (MutableSequence[google.cloud.network_services_v1.types.HttpRoute]): - List of HttpRoute 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 - - http_routes: MutableSequence['HttpRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='HttpRoute', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetHttpRouteRequest(proto.Message): - r"""Request used by the GetHttpRoute method. - - Attributes: - name (str): - Required. A name of the HttpRoute to get. Must be in the - format ``projects/*/locations/global/httpRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateHttpRouteRequest(proto.Message): - r"""Request used by the HttpRoute method. - - Attributes: - parent (str): - Required. The parent resource of the HttpRoute. Must be in - the format ``projects/*/locations/global``. - http_route_id (str): - Required. Short name of the HttpRoute - resource to be created. - http_route (google.cloud.network_services_v1.types.HttpRoute): - Required. HttpRoute resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - http_route_id: str = proto.Field( - proto.STRING, - number=2, - ) - http_route: 'HttpRoute' = proto.Field( - proto.MESSAGE, - number=3, - message='HttpRoute', - ) - - -class UpdateHttpRouteRequest(proto.Message): - r"""Request used by the UpdateHttpRoute method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the HttpRoute 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. - http_route (google.cloud.network_services_v1.types.HttpRoute): - Required. Updated HttpRoute resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - http_route: 'HttpRoute' = proto.Field( - proto.MESSAGE, - number=2, - message='HttpRoute', - ) - - -class DeleteHttpRouteRequest(proto.Message): - r"""Request used by the DeleteHttpRoute method. - - Attributes: - name (str): - Required. A name of the HttpRoute to delete. Must be in the - format ``projects/*/locations/global/httpRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py deleted file mode 100644 index 07ef7d0b3809..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/mesh.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'Mesh', - 'ListMeshesRequest', - 'ListMeshesResponse', - 'GetMeshRequest', - 'CreateMeshRequest', - 'UpdateMeshRequest', - 'DeleteMeshRequest', - }, -) - - -class Mesh(proto.Message): - r"""Mesh represents a logical configuration grouping for workload - to workload communication within a service mesh. Routes that - point to mesh dictate how requests are routed within this - logical mesh boundary. - - Attributes: - name (str): - Required. Name of the Mesh resource. It matches pattern - ``projects/*/locations/global/meshes/``. - self_link (str): - Output only. Server-defined URL of this - 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 Mesh resource. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - interception_port (int): - Optional. If set to a valid TCP port - (1-65535), instructs the SIDECAR proxy to listen - on the specified port of localhost (127.0.0.1) - address. The SIDECAR proxy will expect all - traffic to be redirected to this port regardless - of its actual ip:port destination. If unset, a - port '15001' is used as the interception port. - This is applicable only for sidecar proxy - deployments. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=9, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - interception_port: int = proto.Field( - proto.INT32, - number=8, - ) - - -class ListMeshesRequest(proto.Message): - r"""Request used with the ListMeshes method. - - Attributes: - parent (str): - Required. The project and location from which the Meshes - should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of Meshes to return per call. - page_token (str): - The value returned by the last ``ListMeshesResponse`` - Indicates that this is a continuation of a prior - ``ListMeshes`` 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 ListMeshesResponse(proto.Message): - r"""Response returned by the ListMeshes method. - - Attributes: - meshes (MutableSequence[google.cloud.network_services_v1.types.Mesh]): - List of Mesh 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 - - meshes: MutableSequence['Mesh'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Mesh', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetMeshRequest(proto.Message): - r"""Request used by the GetMesh method. - - Attributes: - name (str): - Required. A name of the Mesh to get. Must be in the format - ``projects/*/locations/global/meshes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateMeshRequest(proto.Message): - r"""Request used by the CreateMesh method. - - Attributes: - parent (str): - Required. The parent resource of the Mesh. Must be in the - format ``projects/*/locations/global``. - mesh_id (str): - Required. Short name of the Mesh resource to - be created. - mesh (google.cloud.network_services_v1.types.Mesh): - Required. Mesh resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - mesh_id: str = proto.Field( - proto.STRING, - number=2, - ) - mesh: 'Mesh' = proto.Field( - proto.MESSAGE, - number=3, - message='Mesh', - ) - - -class UpdateMeshRequest(proto.Message): - r"""Request used by the UpdateMesh method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the Mesh 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. - mesh (google.cloud.network_services_v1.types.Mesh): - Required. Updated Mesh resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - mesh: 'Mesh' = proto.Field( - proto.MESSAGE, - number=2, - message='Mesh', - ) - - -class DeleteMeshRequest(proto.Message): - r"""Request used by the DeleteMesh method. - - Attributes: - name (str): - Required. A name of the Mesh to delete. Must be in the - format ``projects/*/locations/global/meshes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py deleted file mode 100644 index 3e1267789351..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/network_services.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.networkservices.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py deleted file mode 100644 index 50de16c935d9..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/service_binding.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'ServiceBinding', - 'ListServiceBindingsRequest', - 'ListServiceBindingsResponse', - 'GetServiceBindingRequest', - 'CreateServiceBindingRequest', - 'DeleteServiceBindingRequest', - }, -) - - -class ServiceBinding(proto.Message): - r"""ServiceBinding is the resource that defines a Service - Directory Service to be used in a BackendService resource. - - Attributes: - name (str): - Required. Name of the ServiceBinding resource. It matches - pattern - ``projects/*/locations/global/serviceBindings/service_binding_name``. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - 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. - service (str): - Required. The full service directory service name of the - format /projects/*/locations/*/namespaces/*/services/* - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the ServiceBinding resource. - """ - - 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, - ) - service: str = proto.Field( - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - - -class ListServiceBindingsRequest(proto.Message): - r"""Request used with the ListServiceBindings method. - - Attributes: - parent (str): - Required. The project and location from which the - ServiceBindings should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of ServiceBindings to return - per call. - page_token (str): - The value returned by the last - ``ListServiceBindingsResponse`` Indicates that this is a - continuation of a prior ``ListRouters`` 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 ListServiceBindingsResponse(proto.Message): - r"""Response returned by the ListServiceBindings method. - - Attributes: - service_bindings (MutableSequence[google.cloud.network_services_v1.types.ServiceBinding]): - List of ServiceBinding 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 - - service_bindings: MutableSequence['ServiceBinding'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ServiceBinding', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceBindingRequest(proto.Message): - r"""Request used by the GetServiceBinding method. - - Attributes: - name (str): - Required. A name of the ServiceBinding to get. Must be in - the format - ``projects/*/locations/global/serviceBindings/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServiceBindingRequest(proto.Message): - r"""Request used by the ServiceBinding method. - - Attributes: - parent (str): - Required. The parent resource of the ServiceBinding. Must be - in the format ``projects/*/locations/global``. - service_binding_id (str): - Required. Short name of the ServiceBinding - resource to be created. - service_binding (google.cloud.network_services_v1.types.ServiceBinding): - Required. ServiceBinding resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - service_binding_id: str = proto.Field( - proto.STRING, - number=2, - ) - service_binding: 'ServiceBinding' = proto.Field( - proto.MESSAGE, - number=3, - message='ServiceBinding', - ) - - -class DeleteServiceBindingRequest(proto.Message): - r"""Request used by the DeleteServiceBinding method. - - Attributes: - name (str): - Required. A name of the ServiceBinding to delete. Must be in - the format - ``projects/*/locations/global/serviceBindings/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py deleted file mode 100644 index 2f8d72475645..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tcp_route.py +++ /dev/null @@ -1,405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'TcpRoute', - 'ListTcpRoutesRequest', - 'ListTcpRoutesResponse', - 'GetTcpRouteRequest', - 'CreateTcpRouteRequest', - 'UpdateTcpRouteRequest', - 'DeleteTcpRouteRequest', - }, -) - - -class TcpRoute(proto.Message): - r"""TcpRoute is the resource defining how TCP traffic should be - routed by a Mesh/Gateway resource. - - Attributes: - name (str): - Required. Name of the TcpRoute resource. It matches pattern - ``projects/*/locations/global/tcpRoutes/tcp_route_name>``. - self_link (str): - Output only. Server-defined URL of this - 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. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - rules (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteRule]): - Required. Rules that define how traffic is - routed and handled. At least one RouteRule must - be supplied. If there are multiple rules then - the action taken will be the first rule to - match. - meshes (MutableSequence[str]): - Optional. Meshes defines a list of meshes this TcpRoute is - attached to, as one of the routing rules to route the - requests served by the mesh. - - Each mesh reference should match the pattern: - ``projects/*/locations/global/meshes/`` - - The attached Mesh should be of a type SIDECAR - gateways (MutableSequence[str]): - Optional. Gateways defines a list of gateways this TcpRoute - is attached to, as one of the routing rules to route the - requests served by the gateway. - - Each gateway reference should match the pattern: - ``projects/*/locations/global/gateways/`` - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the TcpRoute resource. - """ - - class RouteRule(proto.Message): - r"""Specifies how to match traffic and how to route traffic when - traffic is matched. - - Attributes: - matches (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteMatch]): - Optional. RouteMatch defines the predicate - used to match requests to a given action. - Multiple match types are "OR"ed for evaluation. - If no routeMatch field is specified, this rule - will unconditionally match traffic. - action (google.cloud.network_services_v1.types.TcpRoute.RouteAction): - Required. The detailed rule defining how to - route matched traffic. - """ - - matches: MutableSequence['TcpRoute.RouteMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TcpRoute.RouteMatch', - ) - action: 'TcpRoute.RouteAction' = proto.Field( - proto.MESSAGE, - number=2, - message='TcpRoute.RouteAction', - ) - - class RouteMatch(proto.Message): - r"""RouteMatch defines the predicate used to match requests to a - given action. Multiple match types are "OR"ed for evaluation. If - no routeMatch field is specified, this rule will unconditionally - match traffic. - - Attributes: - address (str): - Required. Must be specified in the CIDR range - format. A CIDR range consists of an IP Address - and a prefix length to construct the subnet - mask. By default, the prefix length is 32 (i.e. - matches a single IP address). Only IPV4 - addresses are supported. - Examples: - - "10.0.0.1" - matches against this exact IP - address. "10.0.0.0/8" - matches against any IP - address within the 10.0.0.0 subnet and - 255.255.255.0 mask. - "0.0.0.0/0" - matches against any IP address'. - port (str): - Required. Specifies the destination port to - match against. - """ - - address: str = proto.Field( - proto.STRING, - number=1, - ) - port: str = proto.Field( - proto.STRING, - number=2, - ) - - class RouteAction(proto.Message): - r"""The specifications for routing traffic and applying - associated policies. - - Attributes: - destinations (MutableSequence[google.cloud.network_services_v1.types.TcpRoute.RouteDestination]): - Optional. The destination services to which - traffic should be forwarded. At least one - destination service is required. Only one of - route destination or original destination can be - set. - original_destination (bool): - Optional. If true, Router will use the - destination IP and port of the original - connection as the destination of the request. - Default is false. Only one of route destinations - or original destination can be set. - """ - - destinations: MutableSequence['TcpRoute.RouteDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TcpRoute.RouteDestination', - ) - original_destination: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class RouteDestination(proto.Message): - r"""Describe the destination for traffic to be routed to. - - Attributes: - service_name (str): - Required. The URL of a BackendService to - route traffic to. - weight (int): - Optional. Specifies the proportion of - requests forwarded to the backend referenced by - the serviceName field. This is computed as: - - - weight/Sum(weights in this destination list). - For non-zero values, there may be some epsilon - from the exact proportion defined here - depending on the precision an implementation - supports. - - If only one serviceName is specified and it has - a weight greater than 0, 100% of the traffic is - forwarded to that backend. - - If weights are specified for any one service - name, they need to be specified for all of them. - - If weights are unspecified for all services, - then, traffic is distributed in equal - proportions to all of them. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - weight: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=11, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - description: str = proto.Field( - proto.STRING, - number=4, - ) - rules: MutableSequence[RouteRule] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=RouteRule, - ) - meshes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - gateways: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -class ListTcpRoutesRequest(proto.Message): - r"""Request used with the ListTcpRoutes method. - - Attributes: - parent (str): - Required. The project and location from which the TcpRoutes - should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of TcpRoutes to return per - call. - page_token (str): - The value returned by the last ``ListTcpRoutesResponse`` - Indicates that this is a continuation of a prior - ``ListTcpRoutes`` 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 ListTcpRoutesResponse(proto.Message): - r"""Response returned by the ListTcpRoutes method. - - Attributes: - tcp_routes (MutableSequence[google.cloud.network_services_v1.types.TcpRoute]): - List of TcpRoute 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 - - tcp_routes: MutableSequence['TcpRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TcpRoute', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTcpRouteRequest(proto.Message): - r"""Request used by the GetTcpRoute method. - - Attributes: - name (str): - Required. A name of the TcpRoute to get. Must be in the - format ``projects/*/locations/global/tcpRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTcpRouteRequest(proto.Message): - r"""Request used by the TcpRoute method. - - Attributes: - parent (str): - Required. The parent resource of the TcpRoute. Must be in - the format ``projects/*/locations/global``. - tcp_route_id (str): - Required. Short name of the TcpRoute resource - to be created. - tcp_route (google.cloud.network_services_v1.types.TcpRoute): - Required. TcpRoute resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - tcp_route_id: str = proto.Field( - proto.STRING, - number=2, - ) - tcp_route: 'TcpRoute' = proto.Field( - proto.MESSAGE, - number=3, - message='TcpRoute', - ) - - -class UpdateTcpRouteRequest(proto.Message): - r"""Request used by the UpdateTcpRoute method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the TcpRoute 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. - tcp_route (google.cloud.network_services_v1.types.TcpRoute): - Required. Updated TcpRoute resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - tcp_route: 'TcpRoute' = proto.Field( - proto.MESSAGE, - number=2, - message='TcpRoute', - ) - - -class DeleteTcpRouteRequest(proto.Message): - r"""Request used by the DeleteTcpRoute method. - - Attributes: - name (str): - Required. A name of the TcpRoute to delete. Must be in the - format ``projects/*/locations/global/tcpRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py b/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py deleted file mode 100644 index dd31245cab16..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/google/cloud/network_services_v1/types/tls_route.py +++ /dev/null @@ -1,366 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.networkservices.v1', - manifest={ - 'TlsRoute', - 'ListTlsRoutesRequest', - 'ListTlsRoutesResponse', - 'GetTlsRouteRequest', - 'CreateTlsRouteRequest', - 'UpdateTlsRouteRequest', - 'DeleteTlsRouteRequest', - }, -) - - -class TlsRoute(proto.Message): - r"""TlsRoute defines how traffic should be routed based on SNI - and other matching L3 attributes. - - Attributes: - name (str): - Required. Name of the TlsRoute resource. It matches pattern - ``projects/*/locations/global/tlsRoutes/tls_route_name>``. - self_link (str): - Output only. Server-defined URL of this - 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. - description (str): - Optional. A free-text description of the - resource. Max length 1024 characters. - rules (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteRule]): - Required. Rules that define how traffic is - routed and handled. At least one RouteRule must - be supplied. If there are multiple rules then - the action taken will be the first rule to - match. - meshes (MutableSequence[str]): - Optional. Meshes defines a list of meshes this TlsRoute is - attached to, as one of the routing rules to route the - requests served by the mesh. - - Each mesh reference should match the pattern: - ``projects/*/locations/global/meshes/`` - - The attached Mesh should be of a type SIDECAR - gateways (MutableSequence[str]): - Optional. Gateways defines a list of gateways this TlsRoute - is attached to, as one of the routing rules to route the - requests served by the gateway. - - Each gateway reference should match the pattern: - ``projects/*/locations/global/gateways/`` - """ - - class RouteRule(proto.Message): - r"""Specifies how to match traffic and how to route traffic when - traffic is matched. - - Attributes: - matches (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteMatch]): - Required. RouteMatch defines the predicate - used to match requests to a given action. - Multiple match types are "OR"ed for evaluation. - action (google.cloud.network_services_v1.types.TlsRoute.RouteAction): - Required. The detailed rule defining how to - route matched traffic. - """ - - matches: MutableSequence['TlsRoute.RouteMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TlsRoute.RouteMatch', - ) - action: 'TlsRoute.RouteAction' = proto.Field( - proto.MESSAGE, - number=2, - message='TlsRoute.RouteAction', - ) - - class RouteMatch(proto.Message): - r"""RouteMatch defines the predicate used to match requests to a - given action. Multiple match types are "AND"ed for evaluation. - If no routeMatch field is specified, this rule will - unconditionally match traffic. - - Attributes: - sni_host (MutableSequence[str]): - Optional. SNI (server name indicator) to match against. SNI - will be matched against all wildcard domains, i.e. - ``www.example.com`` will be first matched against - ``www.example.com``, then ``*.example.com``, then ``*.com.`` - Partial wildcards are not supported, and values like - \*w.example.com are invalid. At least one of sni_host and - alpn is required. Up to 5 sni hosts across all matches can - be set. - alpn (MutableSequence[str]): - Optional. ALPN (Application-Layer Protocol Negotiation) to - match against. Examples: "http/1.1", "h2". At least one of - sni_host and alpn is required. Up to 5 alpns across all - matches can be set. - """ - - sni_host: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - alpn: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class RouteAction(proto.Message): - r"""The specifications for routing traffic and applying - associated policies. - - Attributes: - destinations (MutableSequence[google.cloud.network_services_v1.types.TlsRoute.RouteDestination]): - Required. The destination services to which - traffic should be forwarded. At least one - destination service is required. - """ - - destinations: MutableSequence['TlsRoute.RouteDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TlsRoute.RouteDestination', - ) - - class RouteDestination(proto.Message): - r"""Describe the destination for traffic to be routed to. - - Attributes: - service_name (str): - Required. The URL of a BackendService to - route traffic to. - weight (int): - Optional. Specifies the proportion of requests forwareded to - the backend referenced by the service_name field. This is - computed as: - - - weight/Sum(weights in destinations) Weights in all - destinations does not need to sum up to 100. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - weight: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - self_link: str = proto.Field( - proto.STRING, - number=8, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - description: str = proto.Field( - proto.STRING, - number=4, - ) - rules: MutableSequence[RouteRule] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=RouteRule, - ) - meshes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - gateways: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class ListTlsRoutesRequest(proto.Message): - r"""Request used with the ListTlsRoutes method. - - Attributes: - parent (str): - Required. The project and location from which the TlsRoutes - should be listed, specified in the format - ``projects/*/locations/global``. - page_size (int): - Maximum number of TlsRoutes to return per - call. - page_token (str): - The value returned by the last ``ListTlsRoutesResponse`` - Indicates that this is a continuation of a prior - ``ListTlsRoutes`` 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 ListTlsRoutesResponse(proto.Message): - r"""Response returned by the ListTlsRoutes method. - - Attributes: - tls_routes (MutableSequence[google.cloud.network_services_v1.types.TlsRoute]): - List of TlsRoute 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 - - tls_routes: MutableSequence['TlsRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TlsRoute', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTlsRouteRequest(proto.Message): - r"""Request used by the GetTlsRoute method. - - Attributes: - name (str): - Required. A name of the TlsRoute to get. Must be in the - format ``projects/*/locations/global/tlsRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTlsRouteRequest(proto.Message): - r"""Request used by the TlsRoute method. - - Attributes: - parent (str): - Required. The parent resource of the TlsRoute. Must be in - the format ``projects/*/locations/global``. - tls_route_id (str): - Required. Short name of the TlsRoute resource - to be created. - tls_route (google.cloud.network_services_v1.types.TlsRoute): - Required. TlsRoute resource to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - tls_route_id: str = proto.Field( - proto.STRING, - number=2, - ) - tls_route: 'TlsRoute' = proto.Field( - proto.MESSAGE, - number=3, - message='TlsRoute', - ) - - -class UpdateTlsRouteRequest(proto.Message): - r"""Request used by the UpdateTlsRoute method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the TlsRoute 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. - tls_route (google.cloud.network_services_v1.types.TlsRoute): - Required. Updated TlsRoute resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - tls_route: 'TlsRoute' = proto.Field( - proto.MESSAGE, - number=2, - message='TlsRoute', - ) - - -class DeleteTlsRouteRequest(proto.Message): - r"""Request used by the DeleteTlsRoute method. - - Attributes: - name (str): - Required. A name of the TlsRoute to delete. Must be in the - format ``projects/*/locations/global/tlsRoutes/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-services/v1/mypy.ini b/owl-bot-staging/google-cloud-network-services/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/noxfile.py b/owl-bot-staging/google-cloud-network-services/v1/noxfile.py deleted file mode 100644 index ec43a17e9d50..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/noxfile.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-network-services' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/network_services_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - -@nox.session(python=ALL_PYTHON[-1]) -def prerelease_deps(session): - """Run the unit test suite against pre-release versions of dependencies.""" - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # 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 - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/network_services_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py deleted file mode 100644 index 0ac1307872bf..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_async.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_CreateLbRouteExtension_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_services_v1 - - -async def sample_create_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbRouteExtensionRequest( - parent="parent_value", - lb_route_extension_id="lb_route_extension_id_value", - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.create_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_CreateLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py deleted file mode 100644 index 85540549b0d5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_CreateLbRouteExtension_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_services_v1 - - -def sample_create_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbRouteExtensionRequest( - parent="parent_value", - lb_route_extension_id="lb_route_extension_id_value", - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.create_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_CreateLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py deleted file mode 100644 index 56f616321d1b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_CreateLbTrafficExtension_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_services_v1 - - -async def sample_create_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbTrafficExtensionRequest( - parent="parent_value", - lb_traffic_extension_id="lb_traffic_extension_id_value", - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.create_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_CreateLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py deleted file mode 100644 index bd22c3e94a9b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_CreateLbTrafficExtension_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_services_v1 - - -def sample_create_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.CreateLbTrafficExtensionRequest( - parent="parent_value", - lb_traffic_extension_id="lb_traffic_extension_id_value", - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.create_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_CreateLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py deleted file mode 100644 index cd1a9d0a5c69..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_DeleteLbRouteExtension_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_services_v1 - - -async def sample_delete_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_DeleteLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py deleted file mode 100644 index 5e66f1d86d97..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_DeleteLbRouteExtension_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_services_v1 - - -def sample_delete_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_DeleteLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py deleted file mode 100644 index 6e2e6adf3f1b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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_services_v1 - - -async def sample_delete_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_DeleteLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py deleted file mode 100644 index 626f94d2161d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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_services_v1 - - -def sample_delete_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_DeleteLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py deleted file mode 100644 index 028335cb5d78..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_GetLbRouteExtension_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_services_v1 - - -async def sample_get_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lb_route_extension(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_GetLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py deleted file mode 100644 index 0b2e5dda18bf..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_GetLbRouteExtension_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_services_v1 - - -def sample_get_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbRouteExtensionRequest( - name="name_value", - ) - - # Make the request - response = client.get_lb_route_extension(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_GetLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py deleted file mode 100644 index 00c42981d8db..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_GetLbTrafficExtension_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_services_v1 - - -async def sample_get_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_lb_traffic_extension(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_GetLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py deleted file mode 100644 index 80d91ad3565e..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_GetLbTrafficExtension_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_services_v1 - - -def sample_get_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.GetLbTrafficExtensionRequest( - name="name_value", - ) - - # Make the request - response = client.get_lb_traffic_extension(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_GetLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py deleted file mode 100644 index 593471a93639..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLbRouteExtensions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_ListLbRouteExtensions_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_services_v1 - - -async def sample_list_lb_route_extensions(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbRouteExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_route_extensions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_DepService_ListLbRouteExtensions_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py deleted file mode 100644 index 20871c1d88cc..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLbRouteExtensions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_ListLbRouteExtensions_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_services_v1 - - -def sample_list_lb_route_extensions(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbRouteExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_route_extensions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_DepService_ListLbRouteExtensions_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py deleted file mode 100644 index eae2263dfa61..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLbTrafficExtensions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_ListLbTrafficExtensions_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_services_v1 - - -async def sample_list_lb_traffic_extensions(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbTrafficExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_traffic_extensions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_DepService_ListLbTrafficExtensions_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py deleted file mode 100644 index 47652d7d946d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLbTrafficExtensions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_ListLbTrafficExtensions_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_services_v1 - - -def sample_list_lb_traffic_extensions(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - request = network_services_v1.ListLbTrafficExtensionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_lb_traffic_extensions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_DepService_ListLbTrafficExtensions_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py deleted file mode 100644 index 374babed9c1d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_UpdateLbRouteExtension_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_services_v1 - - -async def sample_update_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbRouteExtensionRequest( - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.update_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_UpdateLbRouteExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py deleted file mode 100644 index f75940b38efd..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateLbRouteExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_UpdateLbRouteExtension_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_services_v1 - - -def sample_update_lb_route_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_route_extension = network_services_v1.LbRouteExtension() - lb_route_extension.name = "name_value" - lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_route_extension.extension_chains.name = "name_value" - lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_route_extension.extension_chains.extensions.name = "name_value" - lb_route_extension.extension_chains.extensions.service = "service_value" - lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbRouteExtensionRequest( - lb_route_extension=lb_route_extension, - ) - - # Make the request - operation = client.update_lb_route_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_UpdateLbRouteExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py deleted file mode 100644 index 315e02bf44d0..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_UpdateLbTrafficExtension_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_services_v1 - - -async def sample_update_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceAsyncClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbTrafficExtensionRequest( - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.update_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_UpdateLbTrafficExtension_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py deleted file mode 100644 index 7857a636ddfb..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateLbTrafficExtension -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_DepService_UpdateLbTrafficExtension_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_services_v1 - - -def sample_update_lb_traffic_extension(): - # Create a client - client = network_services_v1.DepServiceClient() - - # Initialize request argument(s) - lb_traffic_extension = network_services_v1.LbTrafficExtension() - lb_traffic_extension.name = "name_value" - lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] - lb_traffic_extension.extension_chains.name = "name_value" - lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" - lb_traffic_extension.extension_chains.extensions.name = "name_value" - lb_traffic_extension.extension_chains.extensions.service = "service_value" - lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" - - request = network_services_v1.UpdateLbTrafficExtensionRequest( - lb_traffic_extension=lb_traffic_extension, - ) - - # Make the request - operation = client.update_lb_traffic_extension(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_DepService_UpdateLbTrafficExtension_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py deleted file mode 100644 index 4f9088ff8991..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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_services_v1 - - -async def sample_create_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.CreateEndpointPolicyRequest( - parent="parent_value", - endpoint_policy_id="endpoint_policy_id_value", - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.create_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py deleted file mode 100644 index 6a1f52fb8d9e..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_endpoint_policy_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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_services_v1 - - -def sample_create_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.CreateEndpointPolicyRequest( - parent="parent_value", - endpoint_policy_id="endpoint_policy_id_value", - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.create_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py deleted file mode 100644 index 7a22badd7546..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateGateway_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_services_v1 - - -async def sample_create_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.CreateGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - gateway=gateway, - ) - - # Make the request - operation = client.create_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py deleted file mode 100644 index c07d35724f0b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_gateway_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateGateway_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_services_v1 - - -def sample_create_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.CreateGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - gateway=gateway, - ) - - # Make the request - operation = client.create_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py deleted file mode 100644 index db209ff10826..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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_services_v1 - - -async def sample_create_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateGrpcRouteRequest( - parent="parent_value", - grpc_route_id="grpc_route_id_value", - grpc_route=grpc_route, - ) - - # Make the request - operation = client.create_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py deleted file mode 100644 index cb0f154a13d4..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_grpc_route_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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_services_v1 - - -def sample_create_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateGrpcRouteRequest( - parent="parent_value", - grpc_route_id="grpc_route_id_value", - grpc_route=grpc_route, - ) - - # Make the request - operation = client.create_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py deleted file mode 100644 index ff1742598c61..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateHttpRoute_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_services_v1 - - -async def sample_create_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateHttpRouteRequest( - parent="parent_value", - http_route_id="http_route_id_value", - http_route=http_route, - ) - - # Make the request - operation = client.create_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py deleted file mode 100644 index 3d5886a040d5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_http_route_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateHttpRoute_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_services_v1 - - -def sample_create_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.CreateHttpRouteRequest( - parent="parent_value", - http_route_id="http_route_id_value", - http_route=http_route, - ) - - # Make the request - operation = client.create_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py deleted file mode 100644 index cfc92be18af0..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateMesh_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_services_v1 - - -async def sample_create_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.CreateMeshRequest( - parent="parent_value", - mesh_id="mesh_id_value", - mesh=mesh, - ) - - # Make the request - operation = client.create_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py deleted file mode 100644 index f9d0abca3f37..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_mesh_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateMesh_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_services_v1 - - -def sample_create_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.CreateMeshRequest( - parent="parent_value", - mesh_id="mesh_id_value", - mesh=mesh, - ) - - # Make the request - operation = client.create_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py deleted file mode 100644 index c1fb781d3dbc..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateServiceBinding_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_services_v1 - - -async def sample_create_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - service_binding = network_services_v1.ServiceBinding() - service_binding.name = "name_value" - service_binding.service = "service_value" - - request = network_services_v1.CreateServiceBindingRequest( - parent="parent_value", - service_binding_id="service_binding_id_value", - service_binding=service_binding, - ) - - # Make the request - operation = client.create_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py deleted file mode 100644 index e29229e5a6c6..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_service_binding_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateServiceBinding_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_services_v1 - - -def sample_create_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - service_binding = network_services_v1.ServiceBinding() - service_binding.name = "name_value" - service_binding.service = "service_value" - - request = network_services_v1.CreateServiceBindingRequest( - parent="parent_value", - service_binding_id="service_binding_id_value", - service_binding=service_binding, - ) - - # Make the request - operation = client.create_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py deleted file mode 100644 index 1ddb222bebab..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateTcpRoute_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_services_v1 - - -async def sample_create_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.CreateTcpRouteRequest( - parent="parent_value", - tcp_route_id="tcp_route_id_value", - tcp_route=tcp_route, - ) - - # Make the request - operation = client.create_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py deleted file mode 100644 index b87a8f360ae7..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tcp_route_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateTcpRoute_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_services_v1 - - -def sample_create_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.CreateTcpRouteRequest( - parent="parent_value", - tcp_route_id="tcp_route_id_value", - tcp_route=tcp_route, - ) - - # Make the request - operation = client.create_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py deleted file mode 100644 index 1bdb39d13417..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateTlsRoute_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_services_v1 - - -async def sample_create_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.CreateTlsRouteRequest( - parent="parent_value", - tls_route_id="tls_route_id_value", - tls_route=tls_route, - ) - - # Make the request - operation = client.create_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py deleted file mode 100644 index ab46802de1da..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_create_tls_route_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_CreateTlsRoute_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_services_v1 - - -def sample_create_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.CreateTlsRouteRequest( - parent="parent_value", - tls_route_id="tls_route_id_value", - tls_route=tls_route, - ) - - # Make the request - operation = client.create_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_CreateTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py deleted file mode 100644 index ece56b8b6674..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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_services_v1 - - -async def sample_delete_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py deleted file mode 100644 index 0b3da2e0a2b0..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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_services_v1 - - -def sample_delete_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py deleted file mode 100644 index 2aa82831dcd6..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteGateway_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_services_v1 - - -async def sample_delete_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGatewayRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py deleted file mode 100644 index 3a14e483d53d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_gateway_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteGateway_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_services_v1 - - -def sample_delete_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGatewayRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py deleted file mode 100644 index 10669e135a35..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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_services_v1 - - -async def sample_delete_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGrpcRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py deleted file mode 100644 index def384b2c2e7..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_grpc_route_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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_services_v1 - - -def sample_delete_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteGrpcRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py deleted file mode 100644 index 64545a297d68..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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_services_v1 - - -async def sample_delete_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteHttpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py deleted file mode 100644 index 4ddd15a8a2c8..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_http_route_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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_services_v1 - - -def sample_delete_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteHttpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py deleted file mode 100644 index 7bb1b8e4fb2e..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteMesh_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_services_v1 - - -async def sample_delete_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteMeshRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py deleted file mode 100644 index a1b14fc8de90..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_mesh_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteMesh_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_services_v1 - - -def sample_delete_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteMeshRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py deleted file mode 100644 index eb2f26263c58..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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_services_v1 - - -async def sample_delete_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteServiceBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py deleted file mode 100644 index 89cac141e765..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_service_binding_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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_services_v1 - - -def sample_delete_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteServiceBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_service_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py deleted file mode 100644 index 6ac130952227..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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_services_v1 - - -async def sample_delete_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTcpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py deleted file mode 100644 index 352fb49047ba..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tcp_route_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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_services_v1 - - -def sample_delete_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTcpRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py deleted file mode 100644 index 7ae11b3a4636..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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_services_v1 - - -async def sample_delete_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTlsRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py deleted file mode 100644 index fff36a5cae1c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_delete_tls_route_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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_services_v1 - - -def sample_delete_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.DeleteTlsRouteRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_DeleteTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py deleted file mode 100644 index 5e7ac35316ef..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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_services_v1 - - -async def sample_get_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_endpoint_policy(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py deleted file mode 100644 index aa00f4052937..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_endpoint_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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_services_v1 - - -def sample_get_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetEndpointPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_endpoint_policy(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py deleted file mode 100644 index a59cc838519c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetGateway_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_services_v1 - - -async def sample_get_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetGatewayRequest( - name="name_value", - ) - - # Make the request - response = await client.get_gateway(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py deleted file mode 100644 index 35aaea2c5a4a..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_gateway_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetGateway_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_services_v1 - - -def sample_get_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetGatewayRequest( - name="name_value", - ) - - # Make the request - response = client.get_gateway(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py deleted file mode 100644 index 29598f544706..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetGrpcRoute_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_services_v1 - - -async def sample_get_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetGrpcRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_grpc_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py deleted file mode 100644 index ddb18b3086b5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_grpc_route_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetGrpcRoute_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_services_v1 - - -def sample_get_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetGrpcRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_grpc_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py deleted file mode 100644 index 7c3479312dae..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetHttpRoute_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_services_v1 - - -async def sample_get_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetHttpRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_http_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py deleted file mode 100644 index c744123642d0..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_http_route_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetHttpRoute_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_services_v1 - - -def sample_get_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetHttpRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_http_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py deleted file mode 100644 index 263a4ec32a0b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetMesh_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_services_v1 - - -async def sample_get_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetMeshRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mesh(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py deleted file mode 100644 index 3a82f422e6eb..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_mesh_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetMesh_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_services_v1 - - -def sample_get_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetMeshRequest( - name="name_value", - ) - - # Make the request - response = client.get_mesh(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py deleted file mode 100644 index 76cdcd294a2e..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetServiceBinding_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_services_v1 - - -async def sample_get_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetServiceBindingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_service_binding(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetServiceBinding_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py deleted file mode 100644 index 5dc1744327fd..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_service_binding_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetServiceBinding_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_services_v1 - - -def sample_get_service_binding(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetServiceBindingRequest( - name="name_value", - ) - - # Make the request - response = client.get_service_binding(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetServiceBinding_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py deleted file mode 100644 index e82751f4caff..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetTcpRoute_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_services_v1 - - -async def sample_get_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetTcpRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tcp_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py deleted file mode 100644 index fc579ad345e7..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tcp_route_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetTcpRoute_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_services_v1 - - -def sample_get_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetTcpRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_tcp_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py deleted file mode 100644 index ab3f3eddf388..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetTlsRoute_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_services_v1 - - -async def sample_get_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.GetTlsRouteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tls_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py deleted file mode 100644 index 9f7194908f27..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_get_tls_route_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_GetTlsRoute_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_services_v1 - - -def sample_get_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.GetTlsRouteRequest( - name="name_value", - ) - - # Make the request - response = client.get_tls_route(request=request) - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_GetTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py deleted file mode 100644 index d98d0c1c614c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEndpointPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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_services_v1 - - -async def sample_list_endpoint_policies(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListEndpointPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_endpoint_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListEndpointPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py deleted file mode 100644 index 39b5e3ab12b6..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_endpoint_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEndpointPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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_services_v1 - - -def sample_list_endpoint_policies(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListEndpointPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_endpoint_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListEndpointPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py deleted file mode 100644 index 1826f29b8cd4..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGateways -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListGateways_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_services_v1 - - -async def sample_list_gateways(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListGatewaysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gateways(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListGateways_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py deleted file mode 100644 index 801526ab899d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_gateways_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGateways -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListGateways_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_services_v1 - - -def sample_list_gateways(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListGatewaysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gateways(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListGateways_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py deleted file mode 100644 index 439a5b952e25..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGrpcRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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_services_v1 - - -async def sample_list_grpc_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListGrpcRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_grpc_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListGrpcRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py deleted file mode 100644 index 8773d8c7734f..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_grpc_routes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGrpcRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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_services_v1 - - -def sample_list_grpc_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListGrpcRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_grpc_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListGrpcRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py deleted file mode 100644 index 628c246df7ca..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListHttpRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListHttpRoutes_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_services_v1 - - -async def sample_list_http_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListHttpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_http_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListHttpRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py deleted file mode 100644 index 31a44971d681..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_http_routes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListHttpRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListHttpRoutes_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_services_v1 - - -def sample_list_http_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListHttpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_http_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListHttpRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py deleted file mode 100644 index f73783501908..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMeshes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListMeshes_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_services_v1 - - -async def sample_list_meshes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListMeshesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_meshes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListMeshes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py deleted file mode 100644 index 583cf57586e2..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_meshes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMeshes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListMeshes_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_services_v1 - - -def sample_list_meshes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListMeshesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_meshes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListMeshes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py deleted file mode 100644 index f57e5a9a6e35..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceBindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListServiceBindings_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_services_v1 - - -async def sample_list_service_bindings(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListServiceBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_service_bindings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListServiceBindings_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py deleted file mode 100644 index ab0475e0460c..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_service_bindings_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceBindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListServiceBindings_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_services_v1 - - -def sample_list_service_bindings(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListServiceBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_service_bindings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListServiceBindings_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py deleted file mode 100644 index c595de0772ba..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTcpRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListTcpRoutes_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_services_v1 - - -async def sample_list_tcp_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListTcpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tcp_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListTcpRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py deleted file mode 100644 index f96ac04d49ef..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tcp_routes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTcpRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListTcpRoutes_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_services_v1 - - -def sample_list_tcp_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListTcpRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tcp_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListTcpRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py deleted file mode 100644 index 69e2dc5b3fa2..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTlsRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListTlsRoutes_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_services_v1 - - -async def sample_list_tls_routes(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - request = network_services_v1.ListTlsRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tls_routes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListTlsRoutes_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py deleted file mode 100644 index 1fbee93bef58..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_list_tls_routes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTlsRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_ListTlsRoutes_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_services_v1 - - -def sample_list_tls_routes(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - request = network_services_v1.ListTlsRoutesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tls_routes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networkservices_v1_generated_NetworkServices_ListTlsRoutes_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py deleted file mode 100644 index 0596b2a4940d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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_services_v1 - - -async def sample_update_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.UpdateEndpointPolicyRequest( - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.update_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py deleted file mode 100644 index b6d1c512b24a..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_endpoint_policy_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEndpointPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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_services_v1 - - -def sample_update_endpoint_policy(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - endpoint_policy = network_services_v1.EndpointPolicy() - endpoint_policy.name = "name_value" - endpoint_policy.type_ = "GRPC_SERVER" - - request = network_services_v1.UpdateEndpointPolicyRequest( - endpoint_policy=endpoint_policy, - ) - - # Make the request - operation = client.update_endpoint_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py deleted file mode 100644 index 5c2cee43dda9..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateGateway_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_services_v1 - - -async def sample_update_gateway(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.UpdateGatewayRequest( - gateway=gateway, - ) - - # Make the request - operation = client.update_gateway(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateGateway_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py deleted file mode 100644 index 421cd1394a65..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_gateway_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGateway -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateGateway_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_services_v1 - - -def sample_update_gateway(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - gateway = network_services_v1.Gateway() - gateway.name = "name_value" - gateway.ports = [569, 570] - gateway.scope = "scope_value" - - request = network_services_v1.UpdateGatewayRequest( - gateway=gateway, - ) - - # Make the request - operation = client.update_gateway(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateGateway_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py deleted file mode 100644 index e8468acbf671..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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_services_v1 - - -async def sample_update_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateGrpcRouteRequest( - grpc_route=grpc_route, - ) - - # Make the request - operation = client.update_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py deleted file mode 100644 index 3107cd333096..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_grpc_route_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGrpcRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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_services_v1 - - -def sample_update_grpc_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - grpc_route = network_services_v1.GrpcRoute() - grpc_route.name = "name_value" - grpc_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateGrpcRouteRequest( - grpc_route=grpc_route, - ) - - # Make the request - operation = client.update_grpc_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py deleted file mode 100644 index 756ea1acdea3..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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_services_v1 - - -async def sample_update_http_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateHttpRouteRequest( - http_route=http_route, - ) - - # Make the request - operation = client.update_http_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateHttpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py deleted file mode 100644 index a7629cacb114..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_http_route_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateHttpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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_services_v1 - - -def sample_update_http_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - http_route = network_services_v1.HttpRoute() - http_route.name = "name_value" - http_route.hostnames = ['hostnames_value1', 'hostnames_value2'] - - request = network_services_v1.UpdateHttpRouteRequest( - http_route=http_route, - ) - - # Make the request - operation = client.update_http_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateHttpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py deleted file mode 100644 index 95ddc1f62bd1..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateMesh_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_services_v1 - - -async def sample_update_mesh(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.UpdateMeshRequest( - mesh=mesh, - ) - - # Make the request - operation = client.update_mesh(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateMesh_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py deleted file mode 100644 index 5eccc3856f4b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_mesh_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateMesh -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateMesh_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_services_v1 - - -def sample_update_mesh(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - mesh = network_services_v1.Mesh() - mesh.name = "name_value" - - request = network_services_v1.UpdateMeshRequest( - mesh=mesh, - ) - - # Make the request - operation = client.update_mesh(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateMesh_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py deleted file mode 100644 index b16cd417cea1..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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_services_v1 - - -async def sample_update_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.UpdateTcpRouteRequest( - tcp_route=tcp_route, - ) - - # Make the request - operation = client.update_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateTcpRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py deleted file mode 100644 index 59012580671d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tcp_route_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTcpRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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_services_v1 - - -def sample_update_tcp_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tcp_route = network_services_v1.TcpRoute() - tcp_route.name = "name_value" - - request = network_services_v1.UpdateTcpRouteRequest( - tcp_route=tcp_route, - ) - - # Make the request - operation = client.update_tcp_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateTcpRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py deleted file mode 100644 index e28a506bb2a6..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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_services_v1 - - -async def sample_update_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesAsyncClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.UpdateTlsRouteRequest( - tls_route=tls_route, - ) - - # Make the request - operation = client.update_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateTlsRoute_async] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py deleted file mode 100644 index 4f1bf9472f50..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/networkservices_v1_generated_network_services_update_tls_route_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTlsRoute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It 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-services - - -# [START networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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_services_v1 - - -def sample_update_tls_route(): - # Create a client - client = network_services_v1.NetworkServicesClient() - - # Initialize request argument(s) - tls_route = network_services_v1.TlsRoute() - tls_route.name = "name_value" - tls_route.rules.action.destinations.service_name = "service_name_value" - - request = network_services_v1.UpdateTlsRouteRequest( - tls_route=tls_route, - ) - - # Make the request - operation = client.update_tls_route(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networkservices_v1_generated_NetworkServices_UpdateTlsRoute_sync] diff --git a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json b/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json deleted file mode 100644 index 5efe8fa4280b..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json +++ /dev/null @@ -1,8136 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networkservices.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-services", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.create_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.CreateLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "CreateLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lb_route_extension", - "type": "google.cloud.network_services_v1.types.LbRouteExtension" - }, - { - "name": "lb_route_extension_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_lb_route_extension" - }, - "description": "Sample for CreateLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_create_lb_route_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_CreateLbRouteExtension_async", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_create_lb_route_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.create_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.CreateLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "CreateLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateLbRouteExtensionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lb_route_extension", - "type": "google.cloud.network_services_v1.types.LbRouteExtension" - }, - { - "name": "lb_route_extension_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_lb_route_extension" - }, - "description": "Sample for CreateLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_CreateLbRouteExtension_sync", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_create_lb_route_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.create_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.CreateLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "CreateLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lb_traffic_extension", - "type": "google.cloud.network_services_v1.types.LbTrafficExtension" - }, - { - "name": "lb_traffic_extension_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_lb_traffic_extension" - }, - "description": "Sample for CreateLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_CreateLbTrafficExtension_async", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.create_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.CreateLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "CreateLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateLbTrafficExtensionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lb_traffic_extension", - "type": "google.cloud.network_services_v1.types.LbTrafficExtension" - }, - { - "name": "lb_traffic_extension_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_lb_traffic_extension" - }, - "description": "Sample for CreateLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_CreateLbTrafficExtension_sync", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_create_lb_traffic_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.delete_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "DeleteLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_lb_route_extension" - }, - "description": "Sample for DeleteLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_DeleteLbRouteExtension_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": "networkservices_v1_generated_dep_service_delete_lb_route_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.delete_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "DeleteLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteLbRouteExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_lb_route_extension" - }, - "description": "Sample for DeleteLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_DeleteLbRouteExtension_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": "networkservices_v1_generated_dep_service_delete_lb_route_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.delete_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "DeleteLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_lb_traffic_extension" - }, - "description": "Sample for DeleteLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.delete_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.DeleteLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "DeleteLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteLbTrafficExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_lb_traffic_extension" - }, - "description": "Sample for DeleteLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_DeleteLbTrafficExtension_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": "networkservices_v1_generated_dep_service_delete_lb_traffic_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.get_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.GetLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "GetLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetLbRouteExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.LbRouteExtension", - "shortName": "get_lb_route_extension" - }, - "description": "Sample for GetLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_get_lb_route_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_GetLbRouteExtension_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": "networkservices_v1_generated_dep_service_get_lb_route_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.get_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.GetLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "GetLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetLbRouteExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.LbRouteExtension", - "shortName": "get_lb_route_extension" - }, - "description": "Sample for GetLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_GetLbRouteExtension_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": "networkservices_v1_generated_dep_service_get_lb_route_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.get_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.GetLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "GetLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.LbTrafficExtension", - "shortName": "get_lb_traffic_extension" - }, - "description": "Sample for GetLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_GetLbTrafficExtension_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": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.get_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.GetLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "GetLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetLbTrafficExtensionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.LbTrafficExtension", - "shortName": "get_lb_traffic_extension" - }, - "description": "Sample for GetLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_GetLbTrafficExtension_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": "networkservices_v1_generated_dep_service_get_lb_traffic_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.list_lb_route_extensions", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.ListLbRouteExtensions", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "ListLbRouteExtensions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager", - "shortName": "list_lb_route_extensions" - }, - "description": "Sample for ListLbRouteExtensions", - "file": "networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_ListLbRouteExtensions_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": "networkservices_v1_generated_dep_service_list_lb_route_extensions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.list_lb_route_extensions", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.ListLbRouteExtensions", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "ListLbRouteExtensions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListLbRouteExtensionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbRouteExtensionsPager", - "shortName": "list_lb_route_extensions" - }, - "description": "Sample for ListLbRouteExtensions", - "file": "networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_ListLbRouteExtensions_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": "networkservices_v1_generated_dep_service_list_lb_route_extensions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.list_lb_traffic_extensions", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.ListLbTrafficExtensions", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "ListLbTrafficExtensions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager", - "shortName": "list_lb_traffic_extensions" - }, - "description": "Sample for ListLbTrafficExtensions", - "file": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_ListLbTrafficExtensions_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": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.list_lb_traffic_extensions", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.ListLbTrafficExtensions", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "ListLbTrafficExtensions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListLbTrafficExtensionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.dep_service.pagers.ListLbTrafficExtensionsPager", - "shortName": "list_lb_traffic_extensions" - }, - "description": "Sample for ListLbTrafficExtensions", - "file": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_ListLbTrafficExtensions_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": "networkservices_v1_generated_dep_service_list_lb_traffic_extensions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.update_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "UpdateLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest" - }, - { - "name": "lb_route_extension", - "type": "google.cloud.network_services_v1.types.LbRouteExtension" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_lb_route_extension" - }, - "description": "Sample for UpdateLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_update_lb_route_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_UpdateLbRouteExtension_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_update_lb_route_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.update_lb_route_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbRouteExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "UpdateLbRouteExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateLbRouteExtensionRequest" - }, - { - "name": "lb_route_extension", - "type": "google.cloud.network_services_v1.types.LbRouteExtension" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_lb_route_extension" - }, - "description": "Sample for UpdateLbRouteExtension", - "file": "networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_UpdateLbRouteExtension_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_update_lb_route_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient", - "shortName": "DepServiceAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceAsyncClient.update_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "UpdateLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest" - }, - { - "name": "lb_traffic_extension", - "type": "google.cloud.network_services_v1.types.LbTrafficExtension" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_lb_traffic_extension" - }, - "description": "Sample for UpdateLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_UpdateLbTrafficExtension_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.DepServiceClient", - "shortName": "DepServiceClient" - }, - "fullName": "google.cloud.network_services_v1.DepServiceClient.update_lb_traffic_extension", - "method": { - "fullName": "google.cloud.networkservices.v1.DepService.UpdateLbTrafficExtension", - "service": { - "fullName": "google.cloud.networkservices.v1.DepService", - "shortName": "DepService" - }, - "shortName": "UpdateLbTrafficExtension" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateLbTrafficExtensionRequest" - }, - { - "name": "lb_traffic_extension", - "type": "google.cloud.network_services_v1.types.LbTrafficExtension" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_lb_traffic_extension" - }, - "description": "Sample for UpdateLbTrafficExtension", - "file": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_DepService_UpdateLbTrafficExtension_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networkservices_v1_generated_dep_service_update_lb_traffic_extension_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateEndpointPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "endpoint_policy", - "type": "google.cloud.network_services_v1.types.EndpointPolicy" - }, - { - "name": "endpoint_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_endpoint_policy" - }, - "description": "Sample for CreateEndpointPolicy", - "file": "networkservices_v1_generated_network_services_create_endpoint_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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": "networkservices_v1_generated_network_services_create_endpoint_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateEndpointPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "endpoint_policy", - "type": "google.cloud.network_services_v1.types.EndpointPolicy" - }, - { - "name": "endpoint_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_endpoint_policy" - }, - "description": "Sample for CreateEndpointPolicy", - "file": "networkservices_v1_generated_network_services_create_endpoint_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateEndpointPolicy_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": "networkservices_v1_generated_network_services_create_endpoint_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway", - "type": "google.cloud.network_services_v1.types.Gateway" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_gateway" - }, - "description": "Sample for CreateGateway", - "file": "networkservices_v1_generated_network_services_create_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateGateway_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": "networkservices_v1_generated_network_services_create_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway", - "type": "google.cloud.network_services_v1.types.Gateway" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_gateway" - }, - "description": "Sample for CreateGateway", - "file": "networkservices_v1_generated_network_services_create_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateGateway_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": "networkservices_v1_generated_network_services_create_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateGrpcRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "grpc_route", - "type": "google.cloud.network_services_v1.types.GrpcRoute" - }, - { - "name": "grpc_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_grpc_route" - }, - "description": "Sample for CreateGrpcRoute", - "file": "networkservices_v1_generated_network_services_create_grpc_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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": "networkservices_v1_generated_network_services_create_grpc_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateGrpcRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "grpc_route", - "type": "google.cloud.network_services_v1.types.GrpcRoute" - }, - { - "name": "grpc_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_grpc_route" - }, - "description": "Sample for CreateGrpcRoute", - "file": "networkservices_v1_generated_network_services_create_grpc_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateGrpcRoute_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": "networkservices_v1_generated_network_services_create_grpc_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateHttpRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "http_route", - "type": "google.cloud.network_services_v1.types.HttpRoute" - }, - { - "name": "http_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_http_route" - }, - "description": "Sample for CreateHttpRoute", - "file": "networkservices_v1_generated_network_services_create_http_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateHttpRoute_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": "networkservices_v1_generated_network_services_create_http_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateHttpRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "http_route", - "type": "google.cloud.network_services_v1.types.HttpRoute" - }, - { - "name": "http_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_http_route" - }, - "description": "Sample for CreateHttpRoute", - "file": "networkservices_v1_generated_network_services_create_http_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateHttpRoute_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": "networkservices_v1_generated_network_services_create_http_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateMeshRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mesh", - "type": "google.cloud.network_services_v1.types.Mesh" - }, - { - "name": "mesh_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_mesh" - }, - "description": "Sample for CreateMesh", - "file": "networkservices_v1_generated_network_services_create_mesh_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateMesh_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": "networkservices_v1_generated_network_services_create_mesh_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateMeshRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mesh", - "type": "google.cloud.network_services_v1.types.Mesh" - }, - { - "name": "mesh_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_mesh" - }, - "description": "Sample for CreateMesh", - "file": "networkservices_v1_generated_network_services_create_mesh_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateMesh_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": "networkservices_v1_generated_network_services_create_mesh_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateServiceBindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "service_binding", - "type": "google.cloud.network_services_v1.types.ServiceBinding" - }, - { - "name": "service_binding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_service_binding" - }, - "description": "Sample for CreateServiceBinding", - "file": "networkservices_v1_generated_network_services_create_service_binding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateServiceBinding_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": "networkservices_v1_generated_network_services_create_service_binding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateServiceBindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "service_binding", - "type": "google.cloud.network_services_v1.types.ServiceBinding" - }, - { - "name": "service_binding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_service_binding" - }, - "description": "Sample for CreateServiceBinding", - "file": "networkservices_v1_generated_network_services_create_service_binding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateServiceBinding_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": "networkservices_v1_generated_network_services_create_service_binding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateTcpRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tcp_route", - "type": "google.cloud.network_services_v1.types.TcpRoute" - }, - { - "name": "tcp_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_tcp_route" - }, - "description": "Sample for CreateTcpRoute", - "file": "networkservices_v1_generated_network_services_create_tcp_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateTcpRoute_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": "networkservices_v1_generated_network_services_create_tcp_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateTcpRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tcp_route", - "type": "google.cloud.network_services_v1.types.TcpRoute" - }, - { - "name": "tcp_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_tcp_route" - }, - "description": "Sample for CreateTcpRoute", - "file": "networkservices_v1_generated_network_services_create_tcp_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateTcpRoute_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": "networkservices_v1_generated_network_services_create_tcp_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.create_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateTlsRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tls_route", - "type": "google.cloud.network_services_v1.types.TlsRoute" - }, - { - "name": "tls_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_tls_route" - }, - "description": "Sample for CreateTlsRoute", - "file": "networkservices_v1_generated_network_services_create_tls_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateTlsRoute_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": "networkservices_v1_generated_network_services_create_tls_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.create_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.CreateTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "CreateTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.CreateTlsRouteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tls_route", - "type": "google.cloud.network_services_v1.types.TlsRoute" - }, - { - "name": "tls_route_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_tls_route" - }, - "description": "Sample for CreateTlsRoute", - "file": "networkservices_v1_generated_network_services_create_tls_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_CreateTlsRoute_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": "networkservices_v1_generated_network_services_create_tls_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_endpoint_policy" - }, - "description": "Sample for DeleteEndpointPolicy", - "file": "networkservices_v1_generated_network_services_delete_endpoint_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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": "networkservices_v1_generated_network_services_delete_endpoint_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteEndpointPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_endpoint_policy" - }, - "description": "Sample for DeleteEndpointPolicy", - "file": "networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteEndpointPolicy_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": "networkservices_v1_generated_network_services_delete_endpoint_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteGatewayRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_gateway" - }, - "description": "Sample for DeleteGateway", - "file": "networkservices_v1_generated_network_services_delete_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGateway_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": "networkservices_v1_generated_network_services_delete_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteGatewayRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_gateway" - }, - "description": "Sample for DeleteGateway", - "file": "networkservices_v1_generated_network_services_delete_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGateway_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": "networkservices_v1_generated_network_services_delete_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteGrpcRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_grpc_route" - }, - "description": "Sample for DeleteGrpcRoute", - "file": "networkservices_v1_generated_network_services_delete_grpc_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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": "networkservices_v1_generated_network_services_delete_grpc_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteGrpcRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_grpc_route" - }, - "description": "Sample for DeleteGrpcRoute", - "file": "networkservices_v1_generated_network_services_delete_grpc_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteGrpcRoute_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": "networkservices_v1_generated_network_services_delete_grpc_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteHttpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_http_route" - }, - "description": "Sample for DeleteHttpRoute", - "file": "networkservices_v1_generated_network_services_delete_http_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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": "networkservices_v1_generated_network_services_delete_http_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteHttpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_http_route" - }, - "description": "Sample for DeleteHttpRoute", - "file": "networkservices_v1_generated_network_services_delete_http_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteHttpRoute_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": "networkservices_v1_generated_network_services_delete_http_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteMeshRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_mesh" - }, - "description": "Sample for DeleteMesh", - "file": "networkservices_v1_generated_network_services_delete_mesh_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteMesh_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": "networkservices_v1_generated_network_services_delete_mesh_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteMeshRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_mesh" - }, - "description": "Sample for DeleteMesh", - "file": "networkservices_v1_generated_network_services_delete_mesh_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteMesh_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": "networkservices_v1_generated_network_services_delete_mesh_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteServiceBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_service_binding" - }, - "description": "Sample for DeleteServiceBinding", - "file": "networkservices_v1_generated_network_services_delete_service_binding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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": "networkservices_v1_generated_network_services_delete_service_binding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteServiceBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_service_binding" - }, - "description": "Sample for DeleteServiceBinding", - "file": "networkservices_v1_generated_network_services_delete_service_binding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteServiceBinding_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": "networkservices_v1_generated_network_services_delete_service_binding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteTcpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tcp_route" - }, - "description": "Sample for DeleteTcpRoute", - "file": "networkservices_v1_generated_network_services_delete_tcp_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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": "networkservices_v1_generated_network_services_delete_tcp_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteTcpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tcp_route" - }, - "description": "Sample for DeleteTcpRoute", - "file": "networkservices_v1_generated_network_services_delete_tcp_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTcpRoute_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": "networkservices_v1_generated_network_services_delete_tcp_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.delete_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteTlsRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tls_route" - }, - "description": "Sample for DeleteTlsRoute", - "file": "networkservices_v1_generated_network_services_delete_tls_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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": "networkservices_v1_generated_network_services_delete_tls_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.delete_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.DeleteTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "DeleteTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.DeleteTlsRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tls_route" - }, - "description": "Sample for DeleteTlsRoute", - "file": "networkservices_v1_generated_network_services_delete_tls_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_DeleteTlsRoute_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": "networkservices_v1_generated_network_services_delete_tls_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetEndpointPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.EndpointPolicy", - "shortName": "get_endpoint_policy" - }, - "description": "Sample for GetEndpointPolicy", - "file": "networkservices_v1_generated_network_services_get_endpoint_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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": "networkservices_v1_generated_network_services_get_endpoint_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetEndpointPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.EndpointPolicy", - "shortName": "get_endpoint_policy" - }, - "description": "Sample for GetEndpointPolicy", - "file": "networkservices_v1_generated_network_services_get_endpoint_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetEndpointPolicy_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": "networkservices_v1_generated_network_services_get_endpoint_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetGatewayRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.Gateway", - "shortName": "get_gateway" - }, - "description": "Sample for GetGateway", - "file": "networkservices_v1_generated_network_services_get_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetGateway_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": "networkservices_v1_generated_network_services_get_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetGatewayRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.Gateway", - "shortName": "get_gateway" - }, - "description": "Sample for GetGateway", - "file": "networkservices_v1_generated_network_services_get_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetGateway_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": "networkservices_v1_generated_network_services_get_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetGrpcRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.GrpcRoute", - "shortName": "get_grpc_route" - }, - "description": "Sample for GetGrpcRoute", - "file": "networkservices_v1_generated_network_services_get_grpc_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetGrpcRoute_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": "networkservices_v1_generated_network_services_get_grpc_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetGrpcRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.GrpcRoute", - "shortName": "get_grpc_route" - }, - "description": "Sample for GetGrpcRoute", - "file": "networkservices_v1_generated_network_services_get_grpc_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetGrpcRoute_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": "networkservices_v1_generated_network_services_get_grpc_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetHttpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.HttpRoute", - "shortName": "get_http_route" - }, - "description": "Sample for GetHttpRoute", - "file": "networkservices_v1_generated_network_services_get_http_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetHttpRoute_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": "networkservices_v1_generated_network_services_get_http_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetHttpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.HttpRoute", - "shortName": "get_http_route" - }, - "description": "Sample for GetHttpRoute", - "file": "networkservices_v1_generated_network_services_get_http_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetHttpRoute_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": "networkservices_v1_generated_network_services_get_http_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetMeshRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.Mesh", - "shortName": "get_mesh" - }, - "description": "Sample for GetMesh", - "file": "networkservices_v1_generated_network_services_get_mesh_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetMesh_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": "networkservices_v1_generated_network_services_get_mesh_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetMeshRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.Mesh", - "shortName": "get_mesh" - }, - "description": "Sample for GetMesh", - "file": "networkservices_v1_generated_network_services_get_mesh_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetMesh_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": "networkservices_v1_generated_network_services_get_mesh_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetServiceBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.ServiceBinding", - "shortName": "get_service_binding" - }, - "description": "Sample for GetServiceBinding", - "file": "networkservices_v1_generated_network_services_get_service_binding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetServiceBinding_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": "networkservices_v1_generated_network_services_get_service_binding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_service_binding", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetServiceBinding", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetServiceBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetServiceBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.ServiceBinding", - "shortName": "get_service_binding" - }, - "description": "Sample for GetServiceBinding", - "file": "networkservices_v1_generated_network_services_get_service_binding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetServiceBinding_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": "networkservices_v1_generated_network_services_get_service_binding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetTcpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.TcpRoute", - "shortName": "get_tcp_route" - }, - "description": "Sample for GetTcpRoute", - "file": "networkservices_v1_generated_network_services_get_tcp_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetTcpRoute_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": "networkservices_v1_generated_network_services_get_tcp_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetTcpRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.TcpRoute", - "shortName": "get_tcp_route" - }, - "description": "Sample for GetTcpRoute", - "file": "networkservices_v1_generated_network_services_get_tcp_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetTcpRoute_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": "networkservices_v1_generated_network_services_get_tcp_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.get_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetTlsRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.TlsRoute", - "shortName": "get_tls_route" - }, - "description": "Sample for GetTlsRoute", - "file": "networkservices_v1_generated_network_services_get_tls_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetTlsRoute_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": "networkservices_v1_generated_network_services_get_tls_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.get_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.GetTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "GetTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.GetTlsRouteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.types.TlsRoute", - "shortName": "get_tls_route" - }, - "description": "Sample for GetTlsRoute", - "file": "networkservices_v1_generated_network_services_get_tls_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_GetTlsRoute_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": "networkservices_v1_generated_network_services_get_tls_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_endpoint_policies", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListEndpointPolicies", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListEndpointPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListEndpointPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesAsyncPager", - "shortName": "list_endpoint_policies" - }, - "description": "Sample for ListEndpointPolicies", - "file": "networkservices_v1_generated_network_services_list_endpoint_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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": "networkservices_v1_generated_network_services_list_endpoint_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_endpoint_policies", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListEndpointPolicies", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListEndpointPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListEndpointPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListEndpointPoliciesPager", - "shortName": "list_endpoint_policies" - }, - "description": "Sample for ListEndpointPolicies", - "file": "networkservices_v1_generated_network_services_list_endpoint_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListEndpointPolicies_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": "networkservices_v1_generated_network_services_list_endpoint_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_gateways", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGateways", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListGateways" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListGatewaysRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysAsyncPager", - "shortName": "list_gateways" - }, - "description": "Sample for ListGateways", - "file": "networkservices_v1_generated_network_services_list_gateways_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListGateways_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": "networkservices_v1_generated_network_services_list_gateways_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_gateways", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGateways", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListGateways" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListGatewaysRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGatewaysPager", - "shortName": "list_gateways" - }, - "description": "Sample for ListGateways", - "file": "networkservices_v1_generated_network_services_list_gateways_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListGateways_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": "networkservices_v1_generated_network_services_list_gateways_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_grpc_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGrpcRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListGrpcRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListGrpcRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesAsyncPager", - "shortName": "list_grpc_routes" - }, - "description": "Sample for ListGrpcRoutes", - "file": "networkservices_v1_generated_network_services_list_grpc_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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": "networkservices_v1_generated_network_services_list_grpc_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_grpc_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListGrpcRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListGrpcRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListGrpcRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListGrpcRoutesPager", - "shortName": "list_grpc_routes" - }, - "description": "Sample for ListGrpcRoutes", - "file": "networkservices_v1_generated_network_services_list_grpc_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListGrpcRoutes_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": "networkservices_v1_generated_network_services_list_grpc_routes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_http_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListHttpRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListHttpRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListHttpRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesAsyncPager", - "shortName": "list_http_routes" - }, - "description": "Sample for ListHttpRoutes", - "file": "networkservices_v1_generated_network_services_list_http_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListHttpRoutes_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": "networkservices_v1_generated_network_services_list_http_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_http_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListHttpRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListHttpRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListHttpRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListHttpRoutesPager", - "shortName": "list_http_routes" - }, - "description": "Sample for ListHttpRoutes", - "file": "networkservices_v1_generated_network_services_list_http_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListHttpRoutes_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": "networkservices_v1_generated_network_services_list_http_routes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_meshes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListMeshes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListMeshes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListMeshesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListMeshesAsyncPager", - "shortName": "list_meshes" - }, - "description": "Sample for ListMeshes", - "file": "networkservices_v1_generated_network_services_list_meshes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListMeshes_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": "networkservices_v1_generated_network_services_list_meshes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_meshes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListMeshes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListMeshes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListMeshesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListMeshesPager", - "shortName": "list_meshes" - }, - "description": "Sample for ListMeshes", - "file": "networkservices_v1_generated_network_services_list_meshes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListMeshes_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": "networkservices_v1_generated_network_services_list_meshes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_service_bindings", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListServiceBindings", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListServiceBindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListServiceBindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsAsyncPager", - "shortName": "list_service_bindings" - }, - "description": "Sample for ListServiceBindings", - "file": "networkservices_v1_generated_network_services_list_service_bindings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListServiceBindings_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": "networkservices_v1_generated_network_services_list_service_bindings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_service_bindings", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListServiceBindings", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListServiceBindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListServiceBindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListServiceBindingsPager", - "shortName": "list_service_bindings" - }, - "description": "Sample for ListServiceBindings", - "file": "networkservices_v1_generated_network_services_list_service_bindings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListServiceBindings_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": "networkservices_v1_generated_network_services_list_service_bindings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_tcp_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTcpRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListTcpRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListTcpRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesAsyncPager", - "shortName": "list_tcp_routes" - }, - "description": "Sample for ListTcpRoutes", - "file": "networkservices_v1_generated_network_services_list_tcp_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListTcpRoutes_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": "networkservices_v1_generated_network_services_list_tcp_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_tcp_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTcpRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListTcpRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListTcpRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTcpRoutesPager", - "shortName": "list_tcp_routes" - }, - "description": "Sample for ListTcpRoutes", - "file": "networkservices_v1_generated_network_services_list_tcp_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListTcpRoutes_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": "networkservices_v1_generated_network_services_list_tcp_routes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.list_tls_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTlsRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListTlsRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListTlsRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesAsyncPager", - "shortName": "list_tls_routes" - }, - "description": "Sample for ListTlsRoutes", - "file": "networkservices_v1_generated_network_services_list_tls_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListTlsRoutes_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": "networkservices_v1_generated_network_services_list_tls_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.list_tls_routes", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.ListTlsRoutes", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "ListTlsRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.ListTlsRoutesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.network_services_v1.services.network_services.pagers.ListTlsRoutesPager", - "shortName": "list_tls_routes" - }, - "description": "Sample for ListTlsRoutes", - "file": "networkservices_v1_generated_network_services_list_tls_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_ListTlsRoutes_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": "networkservices_v1_generated_network_services_list_tls_routes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest" - }, - { - "name": "endpoint_policy", - "type": "google.cloud.network_services_v1.types.EndpointPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_endpoint_policy" - }, - "description": "Sample for UpdateEndpointPolicy", - "file": "networkservices_v1_generated_network_services_update_endpoint_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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": "networkservices_v1_generated_network_services_update_endpoint_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_endpoint_policy", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateEndpointPolicy", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateEndpointPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateEndpointPolicyRequest" - }, - { - "name": "endpoint_policy", - "type": "google.cloud.network_services_v1.types.EndpointPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_endpoint_policy" - }, - "description": "Sample for UpdateEndpointPolicy", - "file": "networkservices_v1_generated_network_services_update_endpoint_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateEndpointPolicy_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": "networkservices_v1_generated_network_services_update_endpoint_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateGatewayRequest" - }, - { - "name": "gateway", - "type": "google.cloud.network_services_v1.types.Gateway" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_gateway" - }, - "description": "Sample for UpdateGateway", - "file": "networkservices_v1_generated_network_services_update_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGateway_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": "networkservices_v1_generated_network_services_update_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_gateway", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGateway", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateGatewayRequest" - }, - { - "name": "gateway", - "type": "google.cloud.network_services_v1.types.Gateway" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_gateway" - }, - "description": "Sample for UpdateGateway", - "file": "networkservices_v1_generated_network_services_update_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGateway_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": "networkservices_v1_generated_network_services_update_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateGrpcRouteRequest" - }, - { - "name": "grpc_route", - "type": "google.cloud.network_services_v1.types.GrpcRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_grpc_route" - }, - "description": "Sample for UpdateGrpcRoute", - "file": "networkservices_v1_generated_network_services_update_grpc_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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": "networkservices_v1_generated_network_services_update_grpc_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_grpc_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateGrpcRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateGrpcRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateGrpcRouteRequest" - }, - { - "name": "grpc_route", - "type": "google.cloud.network_services_v1.types.GrpcRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_grpc_route" - }, - "description": "Sample for UpdateGrpcRoute", - "file": "networkservices_v1_generated_network_services_update_grpc_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateGrpcRoute_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": "networkservices_v1_generated_network_services_update_grpc_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateHttpRouteRequest" - }, - { - "name": "http_route", - "type": "google.cloud.network_services_v1.types.HttpRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_http_route" - }, - "description": "Sample for UpdateHttpRoute", - "file": "networkservices_v1_generated_network_services_update_http_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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": "networkservices_v1_generated_network_services_update_http_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_http_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateHttpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateHttpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateHttpRouteRequest" - }, - { - "name": "http_route", - "type": "google.cloud.network_services_v1.types.HttpRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_http_route" - }, - "description": "Sample for UpdateHttpRoute", - "file": "networkservices_v1_generated_network_services_update_http_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateHttpRoute_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": "networkservices_v1_generated_network_services_update_http_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateMeshRequest" - }, - { - "name": "mesh", - "type": "google.cloud.network_services_v1.types.Mesh" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_mesh" - }, - "description": "Sample for UpdateMesh", - "file": "networkservices_v1_generated_network_services_update_mesh_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateMesh_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": "networkservices_v1_generated_network_services_update_mesh_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_mesh", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateMesh", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateMesh" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateMeshRequest" - }, - { - "name": "mesh", - "type": "google.cloud.network_services_v1.types.Mesh" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_mesh" - }, - "description": "Sample for UpdateMesh", - "file": "networkservices_v1_generated_network_services_update_mesh_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateMesh_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": "networkservices_v1_generated_network_services_update_mesh_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateTcpRouteRequest" - }, - { - "name": "tcp_route", - "type": "google.cloud.network_services_v1.types.TcpRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_tcp_route" - }, - "description": "Sample for UpdateTcpRoute", - "file": "networkservices_v1_generated_network_services_update_tcp_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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": "networkservices_v1_generated_network_services_update_tcp_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_tcp_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTcpRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateTcpRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateTcpRouteRequest" - }, - { - "name": "tcp_route", - "type": "google.cloud.network_services_v1.types.TcpRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_tcp_route" - }, - "description": "Sample for UpdateTcpRoute", - "file": "networkservices_v1_generated_network_services_update_tcp_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTcpRoute_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": "networkservices_v1_generated_network_services_update_tcp_route_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient", - "shortName": "NetworkServicesAsyncClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesAsyncClient.update_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateTlsRouteRequest" - }, - { - "name": "tls_route", - "type": "google.cloud.network_services_v1.types.TlsRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_tls_route" - }, - "description": "Sample for UpdateTlsRoute", - "file": "networkservices_v1_generated_network_services_update_tls_route_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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": "networkservices_v1_generated_network_services_update_tls_route_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_services_v1.NetworkServicesClient", - "shortName": "NetworkServicesClient" - }, - "fullName": "google.cloud.network_services_v1.NetworkServicesClient.update_tls_route", - "method": { - "fullName": "google.cloud.networkservices.v1.NetworkServices.UpdateTlsRoute", - "service": { - "fullName": "google.cloud.networkservices.v1.NetworkServices", - "shortName": "NetworkServices" - }, - "shortName": "UpdateTlsRoute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_services_v1.types.UpdateTlsRouteRequest" - }, - { - "name": "tls_route", - "type": "google.cloud.network_services_v1.types.TlsRoute" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_tls_route" - }, - "description": "Sample for UpdateTlsRoute", - "file": "networkservices_v1_generated_network_services_update_tls_route_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networkservices_v1_generated_NetworkServices_UpdateTlsRoute_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": "networkservices_v1_generated_network_services_update_tls_route_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py b/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py deleted file mode 100644 index 22a35f3c0c14..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/scripts/fixup_network_services_v1_keywords.py +++ /dev/null @@ -1,224 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_servicesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_endpoint_policy': ('parent', 'endpoint_policy_id', 'endpoint_policy', ), - 'create_gateway': ('parent', 'gateway_id', 'gateway', ), - 'create_grpc_route': ('parent', 'grpc_route_id', 'grpc_route', ), - 'create_http_route': ('parent', 'http_route_id', 'http_route', ), - 'create_lb_route_extension': ('parent', 'lb_route_extension_id', 'lb_route_extension', 'request_id', ), - 'create_lb_traffic_extension': ('parent', 'lb_traffic_extension_id', 'lb_traffic_extension', 'request_id', ), - 'create_mesh': ('parent', 'mesh_id', 'mesh', ), - 'create_service_binding': ('parent', 'service_binding_id', 'service_binding', ), - 'create_tcp_route': ('parent', 'tcp_route_id', 'tcp_route', ), - 'create_tls_route': ('parent', 'tls_route_id', 'tls_route', ), - 'delete_endpoint_policy': ('name', ), - 'delete_gateway': ('name', ), - 'delete_grpc_route': ('name', ), - 'delete_http_route': ('name', ), - 'delete_lb_route_extension': ('name', 'request_id', ), - 'delete_lb_traffic_extension': ('name', 'request_id', ), - 'delete_mesh': ('name', ), - 'delete_service_binding': ('name', ), - 'delete_tcp_route': ('name', ), - 'delete_tls_route': ('name', ), - 'get_endpoint_policy': ('name', ), - 'get_gateway': ('name', ), - 'get_grpc_route': ('name', ), - 'get_http_route': ('name', ), - 'get_lb_route_extension': ('name', ), - 'get_lb_traffic_extension': ('name', ), - 'get_mesh': ('name', ), - 'get_service_binding': ('name', ), - 'get_tcp_route': ('name', ), - 'get_tls_route': ('name', ), - 'list_endpoint_policies': ('parent', 'page_size', 'page_token', ), - 'list_gateways': ('parent', 'page_size', 'page_token', ), - 'list_grpc_routes': ('parent', 'page_size', 'page_token', ), - 'list_http_routes': ('parent', 'page_size', 'page_token', ), - 'list_lb_route_extensions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_lb_traffic_extensions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_meshes': ('parent', 'page_size', 'page_token', ), - 'list_service_bindings': ('parent', 'page_size', 'page_token', ), - 'list_tcp_routes': ('parent', 'page_size', 'page_token', ), - 'list_tls_routes': ('parent', 'page_size', 'page_token', ), - 'update_endpoint_policy': ('endpoint_policy', 'update_mask', ), - 'update_gateway': ('gateway', 'update_mask', ), - 'update_grpc_route': ('grpc_route', 'update_mask', ), - 'update_http_route': ('http_route', 'update_mask', ), - 'update_lb_route_extension': ('lb_route_extension', 'update_mask', 'request_id', ), - 'update_lb_traffic_extension': ('lb_traffic_extension', 'update_mask', 'request_id', ), - 'update_mesh': ('mesh', 'update_mask', ), - 'update_tcp_route': ('tcp_route', 'update_mask', ), - 'update_tls_route': ('tls_route', '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_servicesCallTransformer(), -): - """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_services 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-services/v1/setup.py b/owl-bot-staging/google-cloud-network-services/v1/setup.py deleted file mode 100644 index be59630732e5..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/setup.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services' - - -description = "Google Cloud Network Services API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_services/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.0dev,!=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.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.7.txt deleted file mode 100644 index 4cd2782277d4..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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.0dev", -# 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.19.5 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-services/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-services/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-services/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/tests/unit/gapic/network_services_v1/__init__.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py deleted file mode 100644 index 97c8fdf3643f..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_dep_service.py +++ /dev/null @@ -1,10386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from 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 - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.network_services_v1.services.dep_service import DepServiceAsyncClient -from google.cloud.network_services_v1.services.dep_service import DepServiceClient -from google.cloud.network_services_v1.services.dep_service import pagers -from google.cloud.network_services_v1.services.dep_service import transports -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import dep -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# 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 DepServiceClient._get_default_mtls_endpoint(None) is None - assert DepServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DepServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DepServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DepServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DepServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert DepServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DepServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DepServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DepServiceClient._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 DepServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DepServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DepServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DepServiceClient._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 DepServiceClient._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 DepServiceClient._get_client_cert_source(None, False) is None - assert DepServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DepServiceClient._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 DepServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DepServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) -@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DepServiceClient._DEFAULT_UNIVERSE - default_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DepServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DepServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DepServiceClient.DEFAULT_MTLS_ENDPOINT - assert DepServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DepServiceClient._get_api_endpoint(None, None, default_universe, "always") == DepServiceClient.DEFAULT_MTLS_ENDPOINT - assert DepServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DepServiceClient.DEFAULT_MTLS_ENDPOINT - assert DepServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DepServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DepServiceClient._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 DepServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DepServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DepServiceClient._get_universe_domain(None, None) == DepServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DepServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), - (DepServiceClient, transports.DepServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DepServiceClient, "grpc"), - (DepServiceAsyncClient, "grpc_asyncio"), - (DepServiceClient, "rest"), -]) -def test_dep_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 == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkservices.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DepServiceGrpcTransport, "grpc"), - (transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DepServiceRestTransport, "rest"), -]) -def test_dep_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", [ - (DepServiceClient, "grpc"), - (DepServiceAsyncClient, "grpc_asyncio"), - (DepServiceClient, "rest"), -]) -def test_dep_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 == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkservices.googleapis.com' - ) - - -def test_dep_service_client_get_transport_class(): - transport = DepServiceClient.get_transport_class() - available_transports = [ - transports.DepServiceGrpcTransport, - transports.DepServiceRestTransport, - ] - assert transport in available_transports - - transport = DepServiceClient.get_transport_class("grpc") - assert transport == transports.DepServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DepServiceClient, transports.DepServiceRestTransport, "rest"), -]) -@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) -@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) -def test_dep_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(DepServiceClient, '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(DepServiceClient, '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", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "true"), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "false"), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DepServiceClient, transports.DepServiceRestTransport, "rest", "true"), - (DepServiceClient, transports.DepServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) -@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_dep_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", [ - DepServiceClient, DepServiceAsyncClient -]) -@mock.patch.object(DepServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DepServiceClient)) -@mock.patch.object(DepServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DepServiceAsyncClient)) -def test_dep_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", [ - DepServiceClient, DepServiceAsyncClient -]) -@mock.patch.object(DepServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceClient)) -@mock.patch.object(DepServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DepServiceAsyncClient)) -def test_dep_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DepServiceClient._DEFAULT_UNIVERSE - default_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DepServiceClient._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", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DepServiceClient, transports.DepServiceRestTransport, "rest"), -]) -def test_dep_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", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DepServiceClient, transports.DepServiceRestTransport, "rest", None), -]) -def test_dep_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_dep_service_client_client_options_from_dict(): - with mock.patch('google.cloud.network_services_v1.services.dep_service.transports.DepServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DepServiceClient( - 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", [ - (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_dep_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( - "networkservices.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="networkservices.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - dep.ListLbTrafficExtensionsRequest, - dict, -]) -def test_list_lb_traffic_extensions(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbTrafficExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.ListLbTrafficExtensionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbTrafficExtensionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_lb_traffic_extensions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_lb_traffic_extensions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbTrafficExtensionsRequest() - - -def test_list_lb_traffic_extensions_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 = DepServiceClient( - 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 = dep.ListLbTrafficExtensionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_lb_traffic_extensions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbTrafficExtensionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_lb_traffic_extensions_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 = DepServiceClient( - 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_lb_traffic_extensions 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_lb_traffic_extensions] = mock_rpc - request = {} - client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lb_traffic_extensions(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_lb_traffic_extensions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_lb_traffic_extensions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbTrafficExtensionsRequest() - -@pytest.mark.asyncio -async def test_list_lb_traffic_extensions_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_traffic_extensions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_lb_traffic_extensions] = mock_object - - request = {} - await client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_lb_traffic_extensions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_lb_traffic_extensions_async(transport: str = 'grpc_asyncio', request_type=dep.ListLbTrafficExtensionsRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.ListLbTrafficExtensionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbTrafficExtensionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_lb_traffic_extensions_async_from_dict(): - await test_list_lb_traffic_extensions_async(request_type=dict) - - -def test_list_lb_traffic_extensions_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.ListLbTrafficExtensionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - call.return_value = dep.ListLbTrafficExtensionsResponse() - client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_lb_traffic_extensions_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.ListLbTrafficExtensionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse()) - await client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_lb_traffic_extensions_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbTrafficExtensionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_lb_traffic_extensions( - 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_lb_traffic_extensions_flattened_error(): - client = DepServiceClient( - 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_lb_traffic_extensions( - dep.ListLbTrafficExtensionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_lb_traffic_extensions_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbTrafficExtensionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbTrafficExtensionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_lb_traffic_extensions( - 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_lb_traffic_extensions_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_lb_traffic_extensions( - dep.ListLbTrafficExtensionsRequest(), - parent='parent_value', - ) - - -def test_list_lb_traffic_extensions_pager(transport_name: str = "grpc"): - client = DepServiceClient( - 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_lb_traffic_extensions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - next_page_token='abc', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[], - next_page_token='def', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_lb_traffic_extensions(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dep.LbTrafficExtension) - for i in results) -def test_list_lb_traffic_extensions_pages(transport_name: str = "grpc"): - client = DepServiceClient( - 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_lb_traffic_extensions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - next_page_token='abc', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[], - next_page_token='def', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - ), - RuntimeError, - ) - pages = list(client.list_lb_traffic_extensions(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_lb_traffic_extensions_async_pager(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - next_page_token='abc', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[], - next_page_token='def', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_lb_traffic_extensions(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, dep.LbTrafficExtension) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_lb_traffic_extensions_async_pages(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_traffic_extensions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - next_page_token='abc', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[], - next_page_token='def', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - ), - 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_lb_traffic_extensions(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", [ - dep.GetLbTrafficExtensionRequest, - dict, -]) -def test_get_lb_traffic_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbTrafficExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - ) - response = client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.GetLbTrafficExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbTrafficExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - - -def test_get_lb_traffic_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbTrafficExtensionRequest() - - -def test_get_lb_traffic_extension_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 = DepServiceClient( - 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 = dep.GetLbTrafficExtensionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_lb_traffic_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbTrafficExtensionRequest( - name='name_value', - ) - -def test_get_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - request = {} - client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - )) - response = await client.get_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbTrafficExtensionRequest() - -@pytest.mark.asyncio -async def test_get_lb_traffic_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_traffic_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_lb_traffic_extension] = mock_object - - request = {} - await client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_lb_traffic_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.GetLbTrafficExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - )) - response = await client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.GetLbTrafficExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbTrafficExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - - -@pytest.mark.asyncio -async def test_get_lb_traffic_extension_async_from_dict(): - await test_get_lb_traffic_extension_async(request_type=dict) - - -def test_get_lb_traffic_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.GetLbTrafficExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - call.return_value = dep.LbTrafficExtension() - client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_lb_traffic_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.GetLbTrafficExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension()) - await client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_lb_traffic_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbTrafficExtension() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_lb_traffic_extension( - 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_lb_traffic_extension_flattened_error(): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.GetLbTrafficExtensionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_lb_traffic_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbTrafficExtension() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbTrafficExtension()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_lb_traffic_extension( - 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_lb_traffic_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_lb_traffic_extension( - dep.GetLbTrafficExtensionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.CreateLbTrafficExtensionRequest, - dict, -]) -def test_create_lb_traffic_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.CreateLbTrafficExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_lb_traffic_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbTrafficExtensionRequest() - - -def test_create_lb_traffic_extension_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 = DepServiceClient( - 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 = dep.CreateLbTrafficExtensionRequest( - parent='parent_value', - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_lb_traffic_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbTrafficExtensionRequest( - parent='parent_value', - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - -def test_create_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - request = {} - client.create_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__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_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbTrafficExtensionRequest() - -@pytest.mark.asyncio -async def test_create_lb_traffic_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_traffic_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_lb_traffic_extension] = mock_object - - request = {} - await client.create_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_lb_traffic_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.CreateLbTrafficExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__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_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.CreateLbTrafficExtensionRequest() - 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_lb_traffic_extension_async_from_dict(): - await test_create_lb_traffic_extension_async(request_type=dict) - - -def test_create_lb_traffic_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.CreateLbTrafficExtensionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_lb_traffic_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.CreateLbTrafficExtensionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_lb_traffic_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__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_lb_traffic_extension( - parent='parent_value', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_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].lb_traffic_extension - mock_val = dep.LbTrafficExtension(name='name_value') - assert arg == mock_val - arg = args[0].lb_traffic_extension_id - mock_val = 'lb_traffic_extension_id_value' - assert arg == mock_val - - -def test_create_lb_traffic_extension_flattened_error(): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.CreateLbTrafficExtensionRequest(), - parent='parent_value', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - -@pytest.mark.asyncio -async def test_create_lb_traffic_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_traffic_extension), - '__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_lb_traffic_extension( - parent='parent_value', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_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].lb_traffic_extension - mock_val = dep.LbTrafficExtension(name='name_value') - assert arg == mock_val - arg = args[0].lb_traffic_extension_id - mock_val = 'lb_traffic_extension_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_lb_traffic_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_lb_traffic_extension( - dep.CreateLbTrafficExtensionRequest(), - parent='parent_value', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.UpdateLbTrafficExtensionRequest, - dict, -]) -def test_update_lb_traffic_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.UpdateLbTrafficExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_lb_traffic_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbTrafficExtensionRequest() - - -def test_update_lb_traffic_extension_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 = DepServiceClient( - 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 = dep.UpdateLbTrafficExtensionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_lb_traffic_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbTrafficExtensionRequest( - ) - -def test_update_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - request = {} - client.update_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__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_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbTrafficExtensionRequest() - -@pytest.mark.asyncio -async def test_update_lb_traffic_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_traffic_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_lb_traffic_extension] = mock_object - - request = {} - await client.update_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_lb_traffic_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.UpdateLbTrafficExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__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_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.UpdateLbTrafficExtensionRequest() - 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_lb_traffic_extension_async_from_dict(): - await test_update_lb_traffic_extension_async(request_type=dict) - - -def test_update_lb_traffic_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.UpdateLbTrafficExtensionRequest() - - request.lb_traffic_extension.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'lb_traffic_extension.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_lb_traffic_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.UpdateLbTrafficExtensionRequest() - - request.lb_traffic_extension.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'lb_traffic_extension.name=name_value', - ) in kw['metadata'] - - -def test_update_lb_traffic_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__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_lb_traffic_extension( - lb_traffic_extension=dep.LbTrafficExtension(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].lb_traffic_extension - mock_val = dep.LbTrafficExtension(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_lb_traffic_extension_flattened_error(): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.UpdateLbTrafficExtensionRequest(), - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_lb_traffic_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_traffic_extension), - '__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_lb_traffic_extension( - lb_traffic_extension=dep.LbTrafficExtension(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].lb_traffic_extension - mock_val = dep.LbTrafficExtension(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_lb_traffic_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_lb_traffic_extension( - dep.UpdateLbTrafficExtensionRequest(), - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - dep.DeleteLbTrafficExtensionRequest, - dict, -]) -def test_delete_lb_traffic_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.DeleteLbTrafficExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_lb_traffic_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbTrafficExtensionRequest() - - -def test_delete_lb_traffic_extension_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 = DepServiceClient( - 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 = dep.DeleteLbTrafficExtensionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_lb_traffic_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbTrafficExtensionRequest( - name='name_value', - ) - -def test_delete_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - request = {} - client.delete_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__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_lb_traffic_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbTrafficExtensionRequest() - -@pytest.mark.asyncio -async def test_delete_lb_traffic_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_traffic_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_lb_traffic_extension] = mock_object - - request = {} - await client.delete_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_lb_traffic_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_lb_traffic_extension_async(transport: str = 'grpc_asyncio', request_type=dep.DeleteLbTrafficExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_traffic_extension), - '__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_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.DeleteLbTrafficExtensionRequest() - 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_lb_traffic_extension_async_from_dict(): - await test_delete_lb_traffic_extension_async(request_type=dict) - - -def test_delete_lb_traffic_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.DeleteLbTrafficExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_lb_traffic_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.DeleteLbTrafficExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_lb_traffic_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__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_lb_traffic_extension( - 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_lb_traffic_extension_flattened_error(): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.DeleteLbTrafficExtensionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_lb_traffic_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_traffic_extension), - '__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_lb_traffic_extension( - 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_lb_traffic_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_lb_traffic_extension( - dep.DeleteLbTrafficExtensionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.ListLbRouteExtensionsRequest, - dict, -]) -def test_list_lb_route_extensions(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbRouteExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.ListLbRouteExtensionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbRouteExtensionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_lb_route_extensions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_lb_route_extensions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbRouteExtensionsRequest() - - -def test_list_lb_route_extensions_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 = DepServiceClient( - 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 = dep.ListLbRouteExtensionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_lb_route_extensions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbRouteExtensionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_lb_route_extensions_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 = DepServiceClient( - 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_lb_route_extensions 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_lb_route_extensions] = mock_rpc - request = {} - client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lb_route_extensions(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_lb_route_extensions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_lb_route_extensions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.ListLbRouteExtensionsRequest() - -@pytest.mark.asyncio -async def test_list_lb_route_extensions_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_route_extensions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_lb_route_extensions] = mock_object - - request = {} - await client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_lb_route_extensions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_lb_route_extensions_async(transport: str = 'grpc_asyncio', request_type=dep.ListLbRouteExtensionsRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.ListLbRouteExtensionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbRouteExtensionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_lb_route_extensions_async_from_dict(): - await test_list_lb_route_extensions_async(request_type=dict) - - -def test_list_lb_route_extensions_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.ListLbRouteExtensionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - call.return_value = dep.ListLbRouteExtensionsResponse() - client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_lb_route_extensions_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.ListLbRouteExtensionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse()) - await client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_lb_route_extensions_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbRouteExtensionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_lb_route_extensions( - 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_lb_route_extensions_flattened_error(): - client = DepServiceClient( - 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_lb_route_extensions( - dep.ListLbRouteExtensionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_lb_route_extensions_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.ListLbRouteExtensionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.ListLbRouteExtensionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_lb_route_extensions( - 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_lb_route_extensions_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_lb_route_extensions( - dep.ListLbRouteExtensionsRequest(), - parent='parent_value', - ) - - -def test_list_lb_route_extensions_pager(transport_name: str = "grpc"): - client = DepServiceClient( - 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_lb_route_extensions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - next_page_token='abc', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[], - next_page_token='def', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_lb_route_extensions(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dep.LbRouteExtension) - for i in results) -def test_list_lb_route_extensions_pages(transport_name: str = "grpc"): - client = DepServiceClient( - 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_lb_route_extensions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - next_page_token='abc', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[], - next_page_token='def', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - ), - RuntimeError, - ) - pages = list(client.list_lb_route_extensions(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_lb_route_extensions_async_pager(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - next_page_token='abc', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[], - next_page_token='def', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_lb_route_extensions(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, dep.LbRouteExtension) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_lb_route_extensions_async_pages(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_lb_route_extensions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - next_page_token='abc', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[], - next_page_token='def', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - ), - 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_lb_route_extensions(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", [ - dep.GetLbRouteExtensionRequest, - dict, -]) -def test_get_lb_route_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbRouteExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - ) - response = client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.GetLbRouteExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbRouteExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - - -def test_get_lb_route_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbRouteExtensionRequest() - - -def test_get_lb_route_extension_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 = DepServiceClient( - 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 = dep.GetLbRouteExtensionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_lb_route_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbRouteExtensionRequest( - name='name_value', - ) - -def test_get_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - request = {} - client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lb_route_extension(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_lb_route_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - )) - response = await client.get_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.GetLbRouteExtensionRequest() - -@pytest.mark.asyncio -async def test_get_lb_route_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_route_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_lb_route_extension] = mock_object - - request = {} - await client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_lb_route_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.GetLbRouteExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - )) - response = await client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.GetLbRouteExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbRouteExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - - -@pytest.mark.asyncio -async def test_get_lb_route_extension_async_from_dict(): - await test_get_lb_route_extension_async(request_type=dict) - - -def test_get_lb_route_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.GetLbRouteExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - call.return_value = dep.LbRouteExtension() - client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_lb_route_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.GetLbRouteExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension()) - await client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_lb_route_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbRouteExtension() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_lb_route_extension( - 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_lb_route_extension_flattened_error(): - client = DepServiceClient( - 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_lb_route_extension( - dep.GetLbRouteExtensionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_lb_route_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dep.LbRouteExtension() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dep.LbRouteExtension()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_lb_route_extension( - 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_lb_route_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_lb_route_extension( - dep.GetLbRouteExtensionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.CreateLbRouteExtensionRequest, - dict, -]) -def test_create_lb_route_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.CreateLbRouteExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_lb_route_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbRouteExtensionRequest() - - -def test_create_lb_route_extension_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 = DepServiceClient( - 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 = dep.CreateLbRouteExtensionRequest( - parent='parent_value', - lb_route_extension_id='lb_route_extension_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_lb_route_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbRouteExtensionRequest( - parent='parent_value', - lb_route_extension_id='lb_route_extension_id_value', - ) - -def test_create_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - request = {} - client.create_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__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_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.CreateLbRouteExtensionRequest() - -@pytest.mark.asyncio -async def test_create_lb_route_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_route_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_lb_route_extension] = mock_object - - request = {} - await client.create_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_lb_route_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.CreateLbRouteExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__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_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.CreateLbRouteExtensionRequest() - 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_lb_route_extension_async_from_dict(): - await test_create_lb_route_extension_async(request_type=dict) - - -def test_create_lb_route_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.CreateLbRouteExtensionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_lb_route_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.CreateLbRouteExtensionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_lb_route_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__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_lb_route_extension( - parent='parent_value', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_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].lb_route_extension - mock_val = dep.LbRouteExtension(name='name_value') - assert arg == mock_val - arg = args[0].lb_route_extension_id - mock_val = 'lb_route_extension_id_value' - assert arg == mock_val - - -def test_create_lb_route_extension_flattened_error(): - client = DepServiceClient( - 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_lb_route_extension( - dep.CreateLbRouteExtensionRequest(), - parent='parent_value', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_id_value', - ) - -@pytest.mark.asyncio -async def test_create_lb_route_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_lb_route_extension), - '__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_lb_route_extension( - parent='parent_value', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_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].lb_route_extension - mock_val = dep.LbRouteExtension(name='name_value') - assert arg == mock_val - arg = args[0].lb_route_extension_id - mock_val = 'lb_route_extension_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_lb_route_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_lb_route_extension( - dep.CreateLbRouteExtensionRequest(), - parent='parent_value', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.UpdateLbRouteExtensionRequest, - dict, -]) -def test_update_lb_route_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.UpdateLbRouteExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_lb_route_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbRouteExtensionRequest() - - -def test_update_lb_route_extension_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 = DepServiceClient( - 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 = dep.UpdateLbRouteExtensionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_lb_route_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbRouteExtensionRequest( - ) - -def test_update_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - request = {} - client.update_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__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_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.UpdateLbRouteExtensionRequest() - -@pytest.mark.asyncio -async def test_update_lb_route_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_route_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_lb_route_extension] = mock_object - - request = {} - await client.update_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_lb_route_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.UpdateLbRouteExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__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_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.UpdateLbRouteExtensionRequest() - 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_lb_route_extension_async_from_dict(): - await test_update_lb_route_extension_async(request_type=dict) - - -def test_update_lb_route_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.UpdateLbRouteExtensionRequest() - - request.lb_route_extension.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'lb_route_extension.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_lb_route_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.UpdateLbRouteExtensionRequest() - - request.lb_route_extension.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'lb_route_extension.name=name_value', - ) in kw['metadata'] - - -def test_update_lb_route_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__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_lb_route_extension( - lb_route_extension=dep.LbRouteExtension(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].lb_route_extension - mock_val = dep.LbRouteExtension(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_lb_route_extension_flattened_error(): - client = DepServiceClient( - 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_lb_route_extension( - dep.UpdateLbRouteExtensionRequest(), - lb_route_extension=dep.LbRouteExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_lb_route_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_lb_route_extension), - '__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_lb_route_extension( - lb_route_extension=dep.LbRouteExtension(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].lb_route_extension - mock_val = dep.LbRouteExtension(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_lb_route_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_lb_route_extension( - dep.UpdateLbRouteExtensionRequest(), - lb_route_extension=dep.LbRouteExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - dep.DeleteLbRouteExtensionRequest, - dict, -]) -def test_delete_lb_route_extension(request_type, transport: str = 'grpc'): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = dep.DeleteLbRouteExtensionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_lb_route_extension_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbRouteExtensionRequest() - - -def test_delete_lb_route_extension_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 = DepServiceClient( - 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 = dep.DeleteLbRouteExtensionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_lb_route_extension(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbRouteExtensionRequest( - name='name_value', - ) - -def test_delete_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - request = {} - client.delete_lb_route_extension(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_lb_route_extension(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_lb_route_extension_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__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_lb_route_extension() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dep.DeleteLbRouteExtensionRequest() - -@pytest.mark.asyncio -async def test_delete_lb_route_extension_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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_lb_route_extension in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_lb_route_extension] = mock_object - - request = {} - await client.delete_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_lb_route_extension(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_lb_route_extension_async(transport: str = 'grpc_asyncio', request_type=dep.DeleteLbRouteExtensionRequest): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_lb_route_extension), - '__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_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = dep.DeleteLbRouteExtensionRequest() - 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_lb_route_extension_async_from_dict(): - await test_delete_lb_route_extension_async(request_type=dict) - - -def test_delete_lb_route_extension_field_headers(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.DeleteLbRouteExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_lb_route_extension_field_headers_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dep.DeleteLbRouteExtensionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_lb_route_extension_flattened(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__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_lb_route_extension( - 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_lb_route_extension_flattened_error(): - client = DepServiceClient( - 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_lb_route_extension( - dep.DeleteLbRouteExtensionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_lb_route_extension_flattened_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_lb_route_extension), - '__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_lb_route_extension( - 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_lb_route_extension_flattened_error_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_lb_route_extension( - dep.DeleteLbRouteExtensionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - dep.ListLbTrafficExtensionsRequest, - dict, -]) -def test_list_lb_traffic_extensions_rest(request_type): - client = DepServiceClient( - 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 = dep.ListLbTrafficExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dep.ListLbTrafficExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_lb_traffic_extensions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbTrafficExtensionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - -def test_list_lb_traffic_extensions_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 = DepServiceClient( - 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_lb_traffic_extensions 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_lb_traffic_extensions] = mock_rpc - - request = {} - client.list_lb_traffic_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lb_traffic_extensions(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_lb_traffic_extensions_rest_required_fields(request_type=dep.ListLbTrafficExtensionsRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_traffic_extensions._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_lb_traffic_extensions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dep.ListLbTrafficExtensionsResponse() - # 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 = dep.ListLbTrafficExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_lb_traffic_extensions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_lb_traffic_extensions_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_lb_traffic_extensions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_lb_traffic_extensions_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_list_lb_traffic_extensions") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_list_lb_traffic_extensions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.ListLbTrafficExtensionsRequest.pb(dep.ListLbTrafficExtensionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dep.ListLbTrafficExtensionsResponse.to_json(dep.ListLbTrafficExtensionsResponse()) - - request = dep.ListLbTrafficExtensionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dep.ListLbTrafficExtensionsResponse() - - client.list_lb_traffic_extensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_lb_traffic_extensions_rest_bad_request(transport: str = 'rest', request_type=dep.ListLbTrafficExtensionsRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_lb_traffic_extensions(request) - - -def test_list_lb_traffic_extensions_rest_flattened(): - client = DepServiceClient( - 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 = dep.ListLbTrafficExtensionsResponse() - - # 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 = dep.ListLbTrafficExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_lb_traffic_extensions(**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/*}/lbTrafficExtensions" % client.transport._host, args[1]) - - -def test_list_lb_traffic_extensions_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_traffic_extensions( - dep.ListLbTrafficExtensionsRequest(), - parent='parent_value', - ) - - -def test_list_lb_traffic_extensions_rest_pager(transport: str = 'rest'): - client = DepServiceClient( - 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 = ( - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - next_page_token='abc', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[], - next_page_token='def', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbTrafficExtensionsResponse( - lb_traffic_extensions=[ - dep.LbTrafficExtension(), - dep.LbTrafficExtension(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(dep.ListLbTrafficExtensionsResponse.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_lb_traffic_extensions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dep.LbTrafficExtension) - for i in results) - - pages = list(client.list_lb_traffic_extensions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - dep.GetLbTrafficExtensionRequest, - dict, -]) -def test_get_lb_traffic_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/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 = dep.LbTrafficExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dep.LbTrafficExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_lb_traffic_extension(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbTrafficExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - -def test_get_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - - request = {} - client.get_lb_traffic_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.GetLbTrafficExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dep.LbTrafficExtension() - # 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 = dep.LbTrafficExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_lb_traffic_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_lb_traffic_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_lb_traffic_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_lb_traffic_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_get_lb_traffic_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_get_lb_traffic_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.GetLbTrafficExtensionRequest.pb(dep.GetLbTrafficExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dep.LbTrafficExtension.to_json(dep.LbTrafficExtension()) - - request = dep.GetLbTrafficExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dep.LbTrafficExtension() - - client.get_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.GetLbTrafficExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_lb_traffic_extension(request) - - -def test_get_lb_traffic_extension_rest_flattened(): - client = DepServiceClient( - 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 = dep.LbTrafficExtension() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/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 = dep.LbTrafficExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_lb_traffic_extension(**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/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) - - -def test_get_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.GetLbTrafficExtensionRequest(), - name='name_value', - ) - - -def test_get_lb_traffic_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.CreateLbTrafficExtensionRequest, - dict, -]) -def test_create_lb_traffic_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["lb_traffic_extension"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} - # 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 = dep.CreateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] - - 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["lb_traffic_extension"].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["lb_traffic_extension"][field])): - del request_init["lb_traffic_extension"][field][i][subfield] - else: - del request_init["lb_traffic_extension"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_lb_traffic_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - - request = {} - client.create_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.CreateLbTrafficExtensionRequest): - transport_class = transports.DepServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["lb_traffic_extension_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 "lbTrafficExtensionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_traffic_extension._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "lbTrafficExtensionId" in jsonified_request - assert jsonified_request["lbTrafficExtensionId"] == request_init["lb_traffic_extension_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["lbTrafficExtensionId"] = 'lb_traffic_extension_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_traffic_extension._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("lb_traffic_extension_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 "lbTrafficExtensionId" in jsonified_request - assert jsonified_request["lbTrafficExtensionId"] == 'lb_traffic_extension_id_value' - - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_lb_traffic_extension(request) - - expected_params = [ - ( - "lbTrafficExtensionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_lb_traffic_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_lb_traffic_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("lbTrafficExtensionId", "requestId", )) & set(("parent", "lbTrafficExtensionId", "lbTrafficExtension", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_lb_traffic_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_create_lb_traffic_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_create_lb_traffic_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.CreateLbTrafficExtensionRequest.pb(dep.CreateLbTrafficExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.CreateLbTrafficExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.CreateLbTrafficExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_lb_traffic_extension(request) - - -def test_create_lb_traffic_extension_rest_flattened(): - client = DepServiceClient( - 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', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_lb_traffic_extension(**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/*}/lbTrafficExtensions" % client.transport._host, args[1]) - - -def test_create_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.CreateLbTrafficExtensionRequest(), - parent='parent_value', - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - lb_traffic_extension_id='lb_traffic_extension_id_value', - ) - - -def test_create_lb_traffic_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.UpdateLbTrafficExtensionRequest, - dict, -]) -def test_update_lb_traffic_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} - request_init["lb_traffic_extension"] = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} - # 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 = dep.UpdateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] - - 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["lb_traffic_extension"].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["lb_traffic_extension"][field])): - del request_init["lb_traffic_extension"][field][i][subfield] - else: - del request_init["lb_traffic_extension"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_lb_traffic_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - - request = {} - client.update_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.UpdateLbTrafficExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( - 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 - - response = client.update_lb_traffic_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_lb_traffic_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_lb_traffic_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("lbTrafficExtension", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_lb_traffic_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_update_lb_traffic_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_update_lb_traffic_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.UpdateLbTrafficExtensionRequest.pb(dep.UpdateLbTrafficExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.UpdateLbTrafficExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.UpdateLbTrafficExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_lb_traffic_extension(request) - - -def test_update_lb_traffic_extension_rest_flattened(): - client = DepServiceClient( - 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 = {'lb_traffic_extension': {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - lb_traffic_extension=dep.LbTrafficExtension(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 - - client.update_lb_traffic_extension(**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/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) - - -def test_update_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.UpdateLbTrafficExtensionRequest(), - lb_traffic_extension=dep.LbTrafficExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_lb_traffic_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.DeleteLbTrafficExtensionRequest, - dict, -]) -def test_delete_lb_traffic_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_lb_traffic_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_lb_traffic_extension_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 = DepServiceClient( - 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_lb_traffic_extension 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_lb_traffic_extension] = mock_rpc - - request = {} - client.delete_lb_traffic_extension(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_lb_traffic_extension(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_lb_traffic_extension_rest_required_fields(request_type=dep.DeleteLbTrafficExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_traffic_extension._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_lb_traffic_extension._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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_lb_traffic_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_lb_traffic_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_lb_traffic_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_lb_traffic_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_delete_lb_traffic_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_delete_lb_traffic_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.DeleteLbTrafficExtensionRequest.pb(dep.DeleteLbTrafficExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.DeleteLbTrafficExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_lb_traffic_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_lb_traffic_extension_rest_bad_request(transport: str = 'rest', request_type=dep.DeleteLbTrafficExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbTrafficExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_lb_traffic_extension(request) - - -def test_delete_lb_traffic_extension_rest_flattened(): - client = DepServiceClient( - 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/lbTrafficExtensions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_lb_traffic_extension(**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/*/lbTrafficExtensions/*}" % client.transport._host, args[1]) - - -def test_delete_lb_traffic_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_traffic_extension( - dep.DeleteLbTrafficExtensionRequest(), - name='name_value', - ) - - -def test_delete_lb_traffic_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.ListLbRouteExtensionsRequest, - dict, -]) -def test_list_lb_route_extensions_rest(request_type): - client = DepServiceClient( - 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 = dep.ListLbRouteExtensionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dep.ListLbRouteExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_lb_route_extensions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLbRouteExtensionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - -def test_list_lb_route_extensions_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 = DepServiceClient( - 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_lb_route_extensions 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_lb_route_extensions] = mock_rpc - - request = {} - client.list_lb_route_extensions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_lb_route_extensions(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_lb_route_extensions_rest_required_fields(request_type=dep.ListLbRouteExtensionsRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_route_extensions._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_lb_route_extensions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dep.ListLbRouteExtensionsResponse() - # 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 = dep.ListLbRouteExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_lb_route_extensions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_lb_route_extensions_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_lb_route_extensions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_lb_route_extensions_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_list_lb_route_extensions") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_list_lb_route_extensions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.ListLbRouteExtensionsRequest.pb(dep.ListLbRouteExtensionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dep.ListLbRouteExtensionsResponse.to_json(dep.ListLbRouteExtensionsResponse()) - - request = dep.ListLbRouteExtensionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dep.ListLbRouteExtensionsResponse() - - client.list_lb_route_extensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_lb_route_extensions_rest_bad_request(transport: str = 'rest', request_type=dep.ListLbRouteExtensionsRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_lb_route_extensions(request) - - -def test_list_lb_route_extensions_rest_flattened(): - client = DepServiceClient( - 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 = dep.ListLbRouteExtensionsResponse() - - # 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 = dep.ListLbRouteExtensionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_lb_route_extensions(**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/*}/lbRouteExtensions" % client.transport._host, args[1]) - - -def test_list_lb_route_extensions_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_route_extensions( - dep.ListLbRouteExtensionsRequest(), - parent='parent_value', - ) - - -def test_list_lb_route_extensions_rest_pager(transport: str = 'rest'): - client = DepServiceClient( - 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 = ( - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - next_page_token='abc', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[], - next_page_token='def', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - ], - next_page_token='ghi', - ), - dep.ListLbRouteExtensionsResponse( - lb_route_extensions=[ - dep.LbRouteExtension(), - dep.LbRouteExtension(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(dep.ListLbRouteExtensionsResponse.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_lb_route_extensions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, dep.LbRouteExtension) - for i in results) - - pages = list(client.list_lb_route_extensions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - dep.GetLbRouteExtensionRequest, - dict, -]) -def test_get_lb_route_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/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 = dep.LbRouteExtension( - name='name_value', - description='description_value', - forwarding_rules=['forwarding_rules_value'], - load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = dep.LbRouteExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_lb_route_extension(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, dep.LbRouteExtension) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.forwarding_rules == ['forwarding_rules_value'] - assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED - -def test_get_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - - request = {} - client.get_lb_route_extension(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.GetLbRouteExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = dep.LbRouteExtension() - # 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 = dep.LbRouteExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_lb_route_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_lb_route_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_lb_route_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_lb_route_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_get_lb_route_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_get_lb_route_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.GetLbRouteExtensionRequest.pb(dep.GetLbRouteExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = dep.LbRouteExtension.to_json(dep.LbRouteExtension()) - - request = dep.GetLbRouteExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = dep.LbRouteExtension() - - client.get_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.GetLbRouteExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_lb_route_extension(request) - - -def test_get_lb_route_extension_rest_flattened(): - client = DepServiceClient( - 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 = dep.LbRouteExtension() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/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 = dep.LbRouteExtension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_lb_route_extension(**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/*/lbRouteExtensions/*}" % client.transport._host, args[1]) - - -def test_get_lb_route_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_route_extension( - dep.GetLbRouteExtensionRequest(), - name='name_value', - ) - - -def test_get_lb_route_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.CreateLbRouteExtensionRequest, - dict, -]) -def test_create_lb_route_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["lb_route_extension"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} - # 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 = dep.CreateLbRouteExtensionRequest.meta.fields["lb_route_extension"] - - 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["lb_route_extension"].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["lb_route_extension"][field])): - del request_init["lb_route_extension"][field][i][subfield] - else: - del request_init["lb_route_extension"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_lb_route_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - - request = {} - client.create_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.CreateLbRouteExtensionRequest): - transport_class = transports.DepServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["lb_route_extension_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 "lbRouteExtensionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_route_extension._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "lbRouteExtensionId" in jsonified_request - assert jsonified_request["lbRouteExtensionId"] == request_init["lb_route_extension_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["lbRouteExtensionId"] = 'lb_route_extension_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_lb_route_extension._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("lb_route_extension_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 "lbRouteExtensionId" in jsonified_request - assert jsonified_request["lbRouteExtensionId"] == 'lb_route_extension_id_value' - - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_lb_route_extension(request) - - expected_params = [ - ( - "lbRouteExtensionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_lb_route_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_lb_route_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("lbRouteExtensionId", "requestId", )) & set(("parent", "lbRouteExtensionId", "lbRouteExtension", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_lb_route_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_create_lb_route_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_create_lb_route_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.CreateLbRouteExtensionRequest.pb(dep.CreateLbRouteExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.CreateLbRouteExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.CreateLbRouteExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_lb_route_extension(request) - - -def test_create_lb_route_extension_rest_flattened(): - client = DepServiceClient( - 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', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_lb_route_extension(**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/*}/lbRouteExtensions" % client.transport._host, args[1]) - - -def test_create_lb_route_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_route_extension( - dep.CreateLbRouteExtensionRequest(), - parent='parent_value', - lb_route_extension=dep.LbRouteExtension(name='name_value'), - lb_route_extension_id='lb_route_extension_id_value', - ) - - -def test_create_lb_route_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.UpdateLbRouteExtensionRequest, - dict, -]) -def test_update_lb_route_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} - request_init["lb_route_extension"] = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'labels': {}, 'forwarding_rules': ['forwarding_rules_value1', 'forwarding_rules_value2'], 'extension_chains': [{'name': 'name_value', 'match_condition': {'cel_expression': 'cel_expression_value'}, 'extensions': [{'name': 'name_value', 'authority': 'authority_value', 'service': 'service_value', 'supported_events': [1], 'timeout': {'seconds': 751, 'nanos': 543}, 'fail_open': True, 'forward_headers': ['forward_headers_value1', 'forward_headers_value2']}]}], 'load_balancing_scheme': 1, 'metadata': {'fields': {}}} - # 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 = dep.UpdateLbRouteExtensionRequest.meta.fields["lb_route_extension"] - - 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["lb_route_extension"].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["lb_route_extension"][field])): - del request_init["lb_route_extension"][field][i][subfield] - else: - del request_init["lb_route_extension"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_lb_route_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - - request = {} - client.update_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.UpdateLbRouteExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( - 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 - - response = client.update_lb_route_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_lb_route_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_lb_route_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("lbRouteExtension", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_lb_route_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_update_lb_route_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_update_lb_route_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.UpdateLbRouteExtensionRequest.pb(dep.UpdateLbRouteExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.UpdateLbRouteExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.UpdateLbRouteExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_lb_route_extension(request) - - -def test_update_lb_route_extension_rest_flattened(): - client = DepServiceClient( - 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 = {'lb_route_extension': {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - lb_route_extension=dep.LbRouteExtension(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 - - client.update_lb_route_extension(**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/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}" % client.transport._host, args[1]) - - -def test_update_lb_route_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_route_extension( - dep.UpdateLbRouteExtensionRequest(), - lb_route_extension=dep.LbRouteExtension(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_lb_route_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - dep.DeleteLbRouteExtensionRequest, - dict, -]) -def test_delete_lb_route_extension_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_lb_route_extension(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_lb_route_extension_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 = DepServiceClient( - 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_lb_route_extension 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_lb_route_extension] = mock_rpc - - request = {} - client.delete_lb_route_extension(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_lb_route_extension(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_lb_route_extension_rest_required_fields(request_type=dep.DeleteLbRouteExtensionRequest): - transport_class = transports.DepServiceRestTransport - - 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_lb_route_extension._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_lb_route_extension._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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_lb_route_extension(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_lb_route_extension_rest_unset_required_fields(): - transport = transports.DepServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_lb_route_extension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_lb_route_extension_rest_interceptors(null_interceptor): - transport = transports.DepServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DepServiceRestInterceptor(), - ) - client = DepServiceClient(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.DepServiceRestInterceptor, "post_delete_lb_route_extension") as post, \ - mock.patch.object(transports.DepServiceRestInterceptor, "pre_delete_lb_route_extension") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = dep.DeleteLbRouteExtensionRequest.pb(dep.DeleteLbRouteExtensionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = dep.DeleteLbRouteExtensionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_lb_route_extension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_lb_route_extension_rest_bad_request(transport: str = 'rest', request_type=dep.DeleteLbRouteExtensionRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/lbRouteExtensions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_lb_route_extension(request) - - -def test_delete_lb_route_extension_rest_flattened(): - client = DepServiceClient( - 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/lbRouteExtensions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_lb_route_extension(**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/*/lbRouteExtensions/*}" % client.transport._host, args[1]) - - -def test_delete_lb_route_extension_rest_flattened_error(transport: str = 'rest'): - client = DepServiceClient( - 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_lb_route_extension( - dep.DeleteLbRouteExtensionRequest(), - name='name_value', - ) - - -def test_delete_lb_route_extension_rest_error(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DepServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DepServiceClient( - 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 = DepServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DepServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DepServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DepServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DepServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DepServiceGrpcTransport, - transports.DepServiceGrpcAsyncIOTransport, - transports.DepServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DepServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DepServiceGrpcTransport, - ) - -def test_dep_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DepServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_dep_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_services_v1.services.dep_service.transports.DepServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DepServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_lb_traffic_extensions', - 'get_lb_traffic_extension', - 'create_lb_traffic_extension', - 'update_lb_traffic_extension', - 'delete_lb_traffic_extension', - 'list_lb_route_extensions', - 'get_lb_route_extension', - 'create_lb_route_extension', - 'update_lb_route_extension', - 'delete_lb_route_extension', - '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_dep_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_services_v1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DepServiceTransport( - 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_dep_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_services_v1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DepServiceTransport() - adc.assert_called_once() - - -def test_dep_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) - DepServiceClient() - 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.DepServiceGrpcTransport, - transports.DepServiceGrpcAsyncIOTransport, - ], -) -def test_dep_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.DepServiceGrpcTransport, - transports.DepServiceGrpcAsyncIOTransport, - transports.DepServiceRestTransport, - ], -) -def test_dep_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.DepServiceGrpcTransport, grpc_helpers), - (transports.DepServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_dep_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( - "networkservices.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="networkservices.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) -def test_dep_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_dep_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.DepServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_dep_service_rest_lro_client(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_dep_service_host_no_port(transport_name): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkservices.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_dep_service_host_with_port(transport_name): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkservices.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkservices.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_dep_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DepServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DepServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_lb_traffic_extensions._session - session2 = client2.transport.list_lb_traffic_extensions._session - assert session1 != session2 - session1 = client1.transport.get_lb_traffic_extension._session - session2 = client2.transport.get_lb_traffic_extension._session - assert session1 != session2 - session1 = client1.transport.create_lb_traffic_extension._session - session2 = client2.transport.create_lb_traffic_extension._session - assert session1 != session2 - session1 = client1.transport.update_lb_traffic_extension._session - session2 = client2.transport.update_lb_traffic_extension._session - assert session1 != session2 - session1 = client1.transport.delete_lb_traffic_extension._session - session2 = client2.transport.delete_lb_traffic_extension._session - assert session1 != session2 - session1 = client1.transport.list_lb_route_extensions._session - session2 = client2.transport.list_lb_route_extensions._session - assert session1 != session2 - session1 = client1.transport.get_lb_route_extension._session - session2 = client2.transport.get_lb_route_extension._session - assert session1 != session2 - session1 = client1.transport.create_lb_route_extension._session - session2 = client2.transport.create_lb_route_extension._session - assert session1 != session2 - session1 = client1.transport.update_lb_route_extension._session - session2 = client2.transport.update_lb_route_extension._session - assert session1 != session2 - session1 = client1.transport.delete_lb_route_extension._session - session2 = client2.transport.delete_lb_route_extension._session - assert session1 != session2 -def test_dep_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DepServiceGrpcTransport( - 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_dep_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DepServiceGrpcAsyncIOTransport( - 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.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) -def test_dep_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.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport]) -def test_dep_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_dep_service_grpc_lro_client(): - client = DepServiceClient( - 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_dep_service_grpc_lro_async_client(): - client = DepServiceAsyncClient( - 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_lb_route_extension_path(): - project = "squid" - location = "clam" - lb_route_extension = "whelk" - expected = "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format(project=project, location=location, lb_route_extension=lb_route_extension, ) - actual = DepServiceClient.lb_route_extension_path(project, location, lb_route_extension) - assert expected == actual - - -def test_parse_lb_route_extension_path(): - expected = { - "project": "octopus", - "location": "oyster", - "lb_route_extension": "nudibranch", - } - path = DepServiceClient.lb_route_extension_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_lb_route_extension_path(path) - assert expected == actual - -def test_lb_traffic_extension_path(): - project = "cuttlefish" - location = "mussel" - lb_traffic_extension = "winkle" - expected = "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format(project=project, location=location, lb_traffic_extension=lb_traffic_extension, ) - actual = DepServiceClient.lb_traffic_extension_path(project, location, lb_traffic_extension) - assert expected == actual - - -def test_parse_lb_traffic_extension_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "lb_traffic_extension": "abalone", - } - path = DepServiceClient.lb_traffic_extension_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_lb_traffic_extension_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DepServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DepServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DepServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DepServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DepServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DepServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DepServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DepServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DepServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DepServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DepServiceClient.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.DepServiceTransport, '_prep_wrapped_messages') as prep: - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DepServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DepServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DepServiceClient( - 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 = DepServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DepServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DepServiceClient( - 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", [ - (DepServiceClient, transports.DepServiceGrpcTransport), - (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport), -]) -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-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py b/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py deleted file mode 100644 index a9c63c0e2a90..000000000000 --- a/owl-bot-staging/google-cloud-network-services/v1/tests/unit/gapic/network_services_v1/test_network_services.py +++ /dev/null @@ -1,31441 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from 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 - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.network_services_v1.services.network_services import NetworkServicesAsyncClient -from google.cloud.network_services_v1.services.network_services import NetworkServicesClient -from google.cloud.network_services_v1.services.network_services import pagers -from google.cloud.network_services_v1.services.network_services import transports -from google.cloud.network_services_v1.types import common -from google.cloud.network_services_v1.types import endpoint_policy -from google.cloud.network_services_v1.types import endpoint_policy as gcn_endpoint_policy -from google.cloud.network_services_v1.types import gateway -from google.cloud.network_services_v1.types import gateway as gcn_gateway -from google.cloud.network_services_v1.types import grpc_route -from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route -from google.cloud.network_services_v1.types import http_route -from google.cloud.network_services_v1.types import http_route as gcn_http_route -from google.cloud.network_services_v1.types import mesh -from google.cloud.network_services_v1.types import mesh as gcn_mesh -from google.cloud.network_services_v1.types import service_binding -from google.cloud.network_services_v1.types import service_binding as gcn_service_binding -from google.cloud.network_services_v1.types import tcp_route -from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route -from google.cloud.network_services_v1.types import tls_route -from google.cloud.network_services_v1.types import tls_route as gcn_tls_route -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# 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 NetworkServicesClient._get_default_mtls_endpoint(None) is None - assert NetworkServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert NetworkServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert NetworkServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert NetworkServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert NetworkServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert NetworkServicesClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - NetworkServicesClient._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 NetworkServicesClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert NetworkServicesClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert NetworkServicesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkServicesClient._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 NetworkServicesClient._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 NetworkServicesClient._get_client_cert_source(None, False) is None - assert NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert NetworkServicesClient._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 NetworkServicesClient._get_client_cert_source(None, True) is mock_default_cert_source - assert NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) -@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = NetworkServicesClient._DEFAULT_UNIVERSE - default_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert NetworkServicesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert NetworkServicesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT - assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "always") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT - assert NetworkServicesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkServicesClient.DEFAULT_MTLS_ENDPOINT - assert NetworkServicesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert NetworkServicesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkServicesClient._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 NetworkServicesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert NetworkServicesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert NetworkServicesClient._get_universe_domain(None, None) == NetworkServicesClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - NetworkServicesClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkServicesClient, "grpc"), - (NetworkServicesAsyncClient, "grpc_asyncio"), - (NetworkServicesClient, "rest"), -]) -def test_network_services_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 == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkservices.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.NetworkServicesGrpcTransport, "grpc"), - (transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.NetworkServicesRestTransport, "rest"), -]) -def test_network_services_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", [ - (NetworkServicesClient, "grpc"), - (NetworkServicesAsyncClient, "grpc_asyncio"), - (NetworkServicesClient, "rest"), -]) -def test_network_services_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 == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networkservices.googleapis.com' - ) - - -def test_network_services_client_get_transport_class(): - transport = NetworkServicesClient.get_transport_class() - available_transports = [ - transports.NetworkServicesGrpcTransport, - transports.NetworkServicesRestTransport, - ] - assert transport in available_transports - - transport = NetworkServicesClient.get_transport_class("grpc") - assert transport == transports.NetworkServicesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), -]) -@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) -@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) -def test_network_services_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(NetworkServicesClient, '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(NetworkServicesClient, '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", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", "true"), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", "false"), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", "true"), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", "false"), -]) -@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) -@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_network_services_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", [ - NetworkServicesClient, NetworkServicesAsyncClient -]) -@mock.patch.object(NetworkServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkServicesClient)) -@mock.patch.object(NetworkServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkServicesAsyncClient)) -def test_network_services_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", [ - NetworkServicesClient, NetworkServicesAsyncClient -]) -@mock.patch.object(NetworkServicesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesClient)) -@mock.patch.object(NetworkServicesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkServicesAsyncClient)) -def test_network_services_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = NetworkServicesClient._DEFAULT_UNIVERSE - default_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkServicesClient._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", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), -]) -def test_network_services_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", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", grpc_helpers), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", None), -]) -def test_network_services_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_services_client_client_options_from_dict(): - with mock.patch('google.cloud.network_services_v1.services.network_services.transports.NetworkServicesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = NetworkServicesClient( - 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", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc", grpc_helpers), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_network_services_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( - "networkservices.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="networkservices.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - endpoint_policy.ListEndpointPoliciesRequest, - dict, -]) -def test_list_endpoint_policies(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.ListEndpointPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_endpoint_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = endpoint_policy.ListEndpointPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_endpoint_policies_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_endpoint_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.ListEndpointPoliciesRequest() - - -def test_list_endpoint_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 = NetworkServicesClient( - 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 = endpoint_policy.ListEndpointPoliciesRequest( - 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_endpoint_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_endpoint_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.ListEndpointPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policies] = mock_rpc - request = {} - client.list_endpoint_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_endpoint_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_endpoint_policies_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_endpoint_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.ListEndpointPoliciesRequest() - -@pytest.mark.asyncio -async def test_list_endpoint_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_endpoint_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_endpoint_policies] = mock_object - - request = {} - await client.list_endpoint_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_endpoint_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_endpoint_policies_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.ListEndpointPoliciesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_endpoint_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = endpoint_policy.ListEndpointPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_endpoint_policies_async_from_dict(): - await test_list_endpoint_policies_async(request_type=dict) - - -def test_list_endpoint_policies_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.ListEndpointPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - call.return_value = endpoint_policy.ListEndpointPoliciesResponse() - client.list_endpoint_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_endpoint_policies_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.ListEndpointPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse()) - await client.list_endpoint_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_endpoint_policies_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.ListEndpointPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_endpoint_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_endpoint_policies_flattened_error(): - client = NetworkServicesClient( - 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_endpoint_policies( - endpoint_policy.ListEndpointPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_endpoint_policies_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.ListEndpointPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.ListEndpointPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_endpoint_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_endpoint_policies_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_endpoint_policies( - endpoint_policy.ListEndpointPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_endpoint_policies_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_endpoint_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - next_page_token='abc', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[], - next_page_token='def', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - ], - next_page_token='ghi', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_endpoint_policies(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, endpoint_policy.EndpointPolicy) - for i in results) -def test_list_endpoint_policies_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_endpoint_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - next_page_token='abc', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[], - next_page_token='def', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - ], - next_page_token='ghi', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_endpoint_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_endpoint_policies_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - next_page_token='abc', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[], - next_page_token='def', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - ], - next_page_token='ghi', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_endpoint_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, endpoint_policy.EndpointPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_endpoint_policies_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_endpoint_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - next_page_token='abc', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[], - next_page_token='def', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - ], - next_page_token='ghi', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - ), - 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_endpoint_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", [ - endpoint_policy.GetEndpointPolicyRequest, - dict, -]) -def test_get_endpoint_policy(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.EndpointPolicy( - name='name_value', - type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, - authorization_policy='authorization_policy_value', - description='description_value', - server_tls_policy='server_tls_policy_value', - client_tls_policy='client_tls_policy_value', - ) - response = client.get_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = endpoint_policy.GetEndpointPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint_policy.EndpointPolicy) - assert response.name == 'name_value' - assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY - assert response.authorization_policy == 'authorization_policy_value' - assert response.description == 'description_value' - assert response.server_tls_policy == 'server_tls_policy_value' - assert response.client_tls_policy == 'client_tls_policy_value' - - -def test_get_endpoint_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.GetEndpointPolicyRequest() - - -def test_get_endpoint_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 = NetworkServicesClient( - 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 = endpoint_policy.GetEndpointPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_endpoint_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.GetEndpointPolicyRequest( - name='name_value', - ) - -def test_get_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - request = {} - client.get_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_endpoint_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_endpoint_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy( - name='name_value', - type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, - authorization_policy='authorization_policy_value', - description='description_value', - server_tls_policy='server_tls_policy_value', - client_tls_policy='client_tls_policy_value', - )) - response = await client.get_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.GetEndpointPolicyRequest() - -@pytest.mark.asyncio -async def test_get_endpoint_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_endpoint_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_endpoint_policy] = mock_object - - request = {} - await client.get_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_endpoint_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.GetEndpointPolicyRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy( - name='name_value', - type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, - authorization_policy='authorization_policy_value', - description='description_value', - server_tls_policy='server_tls_policy_value', - client_tls_policy='client_tls_policy_value', - )) - response = await client.get_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = endpoint_policy.GetEndpointPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint_policy.EndpointPolicy) - assert response.name == 'name_value' - assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY - assert response.authorization_policy == 'authorization_policy_value' - assert response.description == 'description_value' - assert response.server_tls_policy == 'server_tls_policy_value' - assert response.client_tls_policy == 'client_tls_policy_value' - - -@pytest.mark.asyncio -async def test_get_endpoint_policy_async_from_dict(): - await test_get_endpoint_policy_async(request_type=dict) - - -def test_get_endpoint_policy_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.GetEndpointPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - call.return_value = endpoint_policy.EndpointPolicy() - client.get_endpoint_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_endpoint_policy_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.GetEndpointPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy()) - await client.get_endpoint_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_endpoint_policy_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.EndpointPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_endpoint_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_endpoint_policy_flattened_error(): - client = NetworkServicesClient( - 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_endpoint_policy( - endpoint_policy.GetEndpointPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_endpoint_policy_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint_policy.EndpointPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint_policy.EndpointPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_endpoint_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_endpoint_policy_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_endpoint_policy( - endpoint_policy.GetEndpointPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_endpoint_policy.CreateEndpointPolicyRequest, - dict, -]) -def test_create_endpoint_policy(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_endpoint_policy.CreateEndpointPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_endpoint_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest() - - -def test_create_endpoint_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 = NetworkServicesClient( - 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_endpoint_policy.CreateEndpointPolicyRequest( - parent='parent_value', - endpoint_policy_id='endpoint_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_endpoint_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest( - parent='parent_value', - endpoint_policy_id='endpoint_policy_id_value', - ) - -def test_create_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - request = {} - client.create_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_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_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.CreateEndpointPolicyRequest() - -@pytest.mark.asyncio -async def test_create_endpoint_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_endpoint_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_endpoint_policy] = mock_object - - request = {} - await client.create_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_endpoint_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_endpoint_policy.CreateEndpointPolicyRequest() - 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_endpoint_policy_async_from_dict(): - await test_create_endpoint_policy_async(request_type=dict) - - -def test_create_endpoint_policy_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_endpoint_policy.CreateEndpointPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_endpoint_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_endpoint_policy_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_endpoint_policy.CreateEndpointPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_endpoint_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_endpoint_policy_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_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_endpoint_policy( - parent='parent_value', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_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].endpoint_policy - mock_val = gcn_endpoint_policy.EndpointPolicy(name='name_value') - assert arg == mock_val - arg = args[0].endpoint_policy_id - mock_val = 'endpoint_policy_id_value' - assert arg == mock_val - - -def test_create_endpoint_policy_flattened_error(): - client = NetworkServicesClient( - 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_endpoint_policy( - gcn_endpoint_policy.CreateEndpointPolicyRequest(), - parent='parent_value', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_endpoint_policy_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_endpoint_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_endpoint_policy( - parent='parent_value', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_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].endpoint_policy - mock_val = gcn_endpoint_policy.EndpointPolicy(name='name_value') - assert arg == mock_val - arg = args[0].endpoint_policy_id - mock_val = 'endpoint_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_endpoint_policy_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_endpoint_policy( - gcn_endpoint_policy.CreateEndpointPolicyRequest(), - parent='parent_value', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_endpoint_policy.UpdateEndpointPolicyRequest, - dict, -]) -def test_update_endpoint_policy(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_endpoint_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest() - - -def test_update_endpoint_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 = NetworkServicesClient( - 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_endpoint_policy.UpdateEndpointPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_endpoint_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest( - ) - -def test_update_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - request = {} - client.update_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_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_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_endpoint_policy.UpdateEndpointPolicyRequest() - -@pytest.mark.asyncio -async def test_update_endpoint_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_endpoint_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_endpoint_policy] = mock_object - - request = {} - await client.update_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_endpoint_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() - 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_endpoint_policy_async_from_dict(): - await test_update_endpoint_policy_async(request_type=dict) - - -def test_update_endpoint_policy_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_endpoint_policy.UpdateEndpointPolicyRequest() - - request.endpoint_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_endpoint_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', - 'endpoint_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_endpoint_policy_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_endpoint_policy.UpdateEndpointPolicyRequest() - - request.endpoint_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_endpoint_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', - 'endpoint_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_endpoint_policy_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_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_endpoint_policy( - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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].endpoint_policy - mock_val = gcn_endpoint_policy.EndpointPolicy(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_endpoint_policy_flattened_error(): - client = NetworkServicesClient( - 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_endpoint_policy( - gcn_endpoint_policy.UpdateEndpointPolicyRequest(), - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_endpoint_policy_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_endpoint_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_endpoint_policy( - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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].endpoint_policy - mock_val = gcn_endpoint_policy.EndpointPolicy(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_endpoint_policy_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_endpoint_policy( - gcn_endpoint_policy.UpdateEndpointPolicyRequest(), - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - endpoint_policy.DeleteEndpointPolicyRequest, - dict, -]) -def test_delete_endpoint_policy(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = endpoint_policy.DeleteEndpointPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_endpoint_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest() - - -def test_delete_endpoint_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 = NetworkServicesClient( - 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 = endpoint_policy.DeleteEndpointPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_endpoint_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest( - name='name_value', - ) - -def test_delete_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - request = {} - client.delete_endpoint_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_endpoint_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_endpoint_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_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_endpoint_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == endpoint_policy.DeleteEndpointPolicyRequest() - -@pytest.mark.asyncio -async def test_delete_endpoint_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_endpoint_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_endpoint_policy] = mock_object - - request = {} - await client.delete_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_endpoint_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_endpoint_policy_async(transport: str = 'grpc_asyncio', request_type=endpoint_policy.DeleteEndpointPolicyRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_endpoint_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_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = endpoint_policy.DeleteEndpointPolicyRequest() - 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_endpoint_policy_async_from_dict(): - await test_delete_endpoint_policy_async(request_type=dict) - - -def test_delete_endpoint_policy_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.DeleteEndpointPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_endpoint_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_endpoint_policy_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = endpoint_policy.DeleteEndpointPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_endpoint_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_endpoint_policy_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_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_endpoint_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_endpoint_policy_flattened_error(): - client = NetworkServicesClient( - 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_endpoint_policy( - endpoint_policy.DeleteEndpointPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_endpoint_policy_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_endpoint_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_endpoint_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_endpoint_policy_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_endpoint_policy( - endpoint_policy.DeleteEndpointPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gateway.ListGatewaysRequest, - dict, -]) -def test_list_gateways(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateways), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.ListGatewaysResponse( - next_page_token='next_page_token_value', - ) - response = client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gateway.ListGatewaysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGatewaysPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_gateways_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_gateways() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.ListGatewaysRequest() - - -def test_list_gateways_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 = NetworkServicesClient( - 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 = gateway.ListGatewaysRequest( - 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_gateways), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_gateways(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.ListGatewaysRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_gateways_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 = NetworkServicesClient( - 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_gateways 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_gateways] = mock_rpc - request = {} - client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_gateways(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_gateways_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_gateways() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.ListGatewaysRequest() - -@pytest.mark.asyncio -async def test_list_gateways_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_gateways in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_gateways] = mock_object - - request = {} - await client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_gateways(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_gateways_async(transport: str = 'grpc_asyncio', request_type=gateway.ListGatewaysRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateways), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gateway.ListGatewaysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGatewaysAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_gateways_async_from_dict(): - await test_list_gateways_async(request_type=dict) - - -def test_list_gateways_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.ListGatewaysRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - call.return_value = gateway.ListGatewaysResponse() - client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_gateways_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.ListGatewaysRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse()) - await client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_gateways_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.ListGatewaysResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_gateways( - 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_gateways_flattened_error(): - client = NetworkServicesClient( - 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_gateways( - gateway.ListGatewaysRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_gateways_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.ListGatewaysResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.ListGatewaysResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_gateways( - 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_gateways_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_gateways( - gateway.ListGatewaysRequest(), - parent='parent_value', - ) - - -def test_list_gateways_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_gateways), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - gateway.Gateway(), - ], - next_page_token='abc', - ), - gateway.ListGatewaysResponse( - gateways=[], - next_page_token='def', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - ], - next_page_token='ghi', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_gateways(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gateway.Gateway) - for i in results) -def test_list_gateways_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_gateways), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - gateway.Gateway(), - ], - next_page_token='abc', - ), - gateway.ListGatewaysResponse( - gateways=[], - next_page_token='def', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - ], - next_page_token='ghi', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - ], - ), - RuntimeError, - ) - pages = list(client.list_gateways(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_gateways_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - gateway.Gateway(), - ], - next_page_token='abc', - ), - gateway.ListGatewaysResponse( - gateways=[], - next_page_token='def', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - ], - next_page_token='ghi', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_gateways(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, gateway.Gateway) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_gateways_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gateways), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - gateway.Gateway(), - ], - next_page_token='abc', - ), - gateway.ListGatewaysResponse( - gateways=[], - next_page_token='def', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - ], - next_page_token='ghi', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - ], - ), - 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_gateways(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", [ - gateway.GetGatewayRequest, - dict, -]) -def test_get_gateway(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.Gateway( - name='name_value', - self_link='self_link_value', - description='description_value', - type_=gateway.Gateway.Type.OPEN_MESH, - ports=[568], - scope='scope_value', - server_tls_policy='server_tls_policy_value', - ) - response = client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gateway.GetGatewayRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gateway.Gateway) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.type_ == gateway.Gateway.Type.OPEN_MESH - assert response.ports == [568] - assert response.scope == 'scope_value' - assert response.server_tls_policy == 'server_tls_policy_value' - - -def test_get_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.GetGatewayRequest() - - -def test_get_gateway_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 = NetworkServicesClient( - 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 = gateway.GetGatewayRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_gateway(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.GetGatewayRequest( - name='name_value', - ) - -def test_get_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - request = {} - client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_gateway(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_gateway_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway( - name='name_value', - self_link='self_link_value', - description='description_value', - type_=gateway.Gateway.Type.OPEN_MESH, - ports=[568], - scope='scope_value', - server_tls_policy='server_tls_policy_value', - )) - response = await client.get_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.GetGatewayRequest() - -@pytest.mark.asyncio -async def test_get_gateway_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_gateway in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_gateway] = mock_object - - request = {} - await client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_gateway(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_gateway_async(transport: str = 'grpc_asyncio', request_type=gateway.GetGatewayRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway( - name='name_value', - self_link='self_link_value', - description='description_value', - type_=gateway.Gateway.Type.OPEN_MESH, - ports=[568], - scope='scope_value', - server_tls_policy='server_tls_policy_value', - )) - response = await client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gateway.GetGatewayRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gateway.Gateway) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.type_ == gateway.Gateway.Type.OPEN_MESH - assert response.ports == [568] - assert response.scope == 'scope_value' - assert response.server_tls_policy == 'server_tls_policy_value' - - -@pytest.mark.asyncio -async def test_get_gateway_async_from_dict(): - await test_get_gateway_async(request_type=dict) - - -def test_get_gateway_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.GetGatewayRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - call.return_value = gateway.Gateway() - client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_gateway_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.GetGatewayRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway()) - await client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_gateway_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.Gateway() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_gateway( - 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_gateway_flattened_error(): - client = NetworkServicesClient( - 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_gateway( - gateway.GetGatewayRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_gateway_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gateway.Gateway() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gateway.Gateway()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_gateway( - 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_gateway_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_gateway( - gateway.GetGatewayRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_gateway.CreateGatewayRequest, - dict, -]) -def test_create_gateway(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_gateway.CreateGatewayRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.CreateGatewayRequest() - - -def test_create_gateway_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 = NetworkServicesClient( - 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_gateway.CreateGatewayRequest( - parent='parent_value', - gateway_id='gateway_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_gateway(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.CreateGatewayRequest( - parent='parent_value', - gateway_id='gateway_id_value', - ) - -def test_create_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - request = {} - client.create_gateway(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_gateway(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_gateway_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__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_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.CreateGatewayRequest() - -@pytest.mark.asyncio -async def test_create_gateway_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_gateway in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_gateway] = mock_object - - request = {} - await client.create_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_gateway(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_gateway_async(transport: str = 'grpc_asyncio', request_type=gcn_gateway.CreateGatewayRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__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_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_gateway.CreateGatewayRequest() - 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_gateway_async_from_dict(): - await test_create_gateway_async(request_type=dict) - - -def test_create_gateway_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_gateway.CreateGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_gateway_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_gateway.CreateGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_gateway_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__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_gateway( - parent='parent_value', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_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].gateway - mock_val = gcn_gateway.Gateway(name='name_value') - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - - -def test_create_gateway_flattened_error(): - client = NetworkServicesClient( - 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_gateway( - gcn_gateway.CreateGatewayRequest(), - parent='parent_value', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_id_value', - ) - -@pytest.mark.asyncio -async def test_create_gateway_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_gateway), - '__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_gateway( - parent='parent_value', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_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].gateway - mock_val = gcn_gateway.Gateway(name='name_value') - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_gateway_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_gateway( - gcn_gateway.CreateGatewayRequest(), - parent='parent_value', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_gateway.UpdateGatewayRequest, - dict, -]) -def test_update_gateway(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_gateway.UpdateGatewayRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.UpdateGatewayRequest() - - -def test_update_gateway_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 = NetworkServicesClient( - 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_gateway.UpdateGatewayRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_gateway(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.UpdateGatewayRequest( - ) - -def test_update_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - request = {} - client.update_gateway(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_gateway(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_gateway_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__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_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_gateway.UpdateGatewayRequest() - -@pytest.mark.asyncio -async def test_update_gateway_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_gateway in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_gateway] = mock_object - - request = {} - await client.update_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_gateway(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_gateway_async(transport: str = 'grpc_asyncio', request_type=gcn_gateway.UpdateGatewayRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__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_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_gateway.UpdateGatewayRequest() - 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_gateway_async_from_dict(): - await test_update_gateway_async(request_type=dict) - - -def test_update_gateway_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_gateway.UpdateGatewayRequest() - - request.gateway.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'gateway.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_gateway_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_gateway.UpdateGatewayRequest() - - request.gateway.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'gateway.name=name_value', - ) in kw['metadata'] - - -def test_update_gateway_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__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_gateway( - gateway=gcn_gateway.Gateway(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].gateway - mock_val = gcn_gateway.Gateway(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_gateway_flattened_error(): - client = NetworkServicesClient( - 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_gateway( - gcn_gateway.UpdateGatewayRequest(), - gateway=gcn_gateway.Gateway(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_gateway_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_gateway), - '__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_gateway( - gateway=gcn_gateway.Gateway(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].gateway - mock_val = gcn_gateway.Gateway(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_gateway_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_gateway( - gcn_gateway.UpdateGatewayRequest(), - gateway=gcn_gateway.Gateway(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - gateway.DeleteGatewayRequest, - dict, -]) -def test_delete_gateway(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gateway.DeleteGatewayRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.DeleteGatewayRequest() - - -def test_delete_gateway_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 = NetworkServicesClient( - 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 = gateway.DeleteGatewayRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_gateway(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.DeleteGatewayRequest( - name='name_value', - ) - -def test_delete_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - request = {} - client.delete_gateway(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_gateway(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_gateway_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__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_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gateway.DeleteGatewayRequest() - -@pytest.mark.asyncio -async def test_delete_gateway_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_gateway in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_gateway] = mock_object - - request = {} - await client.delete_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_gateway(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_gateway_async(transport: str = 'grpc_asyncio', request_type=gateway.DeleteGatewayRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_gateway), - '__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_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gateway.DeleteGatewayRequest() - 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_gateway_async_from_dict(): - await test_delete_gateway_async(request_type=dict) - - -def test_delete_gateway_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.DeleteGatewayRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_gateway_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gateway.DeleteGatewayRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_gateway_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__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_gateway( - 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_gateway_flattened_error(): - client = NetworkServicesClient( - 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_gateway( - gateway.DeleteGatewayRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_gateway_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_gateway), - '__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_gateway( - 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_gateway_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_gateway( - gateway.DeleteGatewayRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - grpc_route.ListGrpcRoutesRequest, - dict, -]) -def test_list_grpc_routes(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.ListGrpcRoutesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grpc_route.ListGrpcRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGrpcRoutesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_grpc_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_grpc_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.ListGrpcRoutesRequest() - - -def test_list_grpc_routes_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 = NetworkServicesClient( - 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 = grpc_route.ListGrpcRoutesRequest( - 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_grpc_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_grpc_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.ListGrpcRoutesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_grpc_routes_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 = NetworkServicesClient( - 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_grpc_routes 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_grpc_routes] = mock_rpc - request = {} - client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_grpc_routes(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_grpc_routes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_grpc_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.ListGrpcRoutesRequest() - -@pytest.mark.asyncio -async def test_list_grpc_routes_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_grpc_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_grpc_routes] = mock_object - - request = {} - await client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_grpc_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_grpc_routes_async(transport: str = 'grpc_asyncio', request_type=grpc_route.ListGrpcRoutesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grpc_route.ListGrpcRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGrpcRoutesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_grpc_routes_async_from_dict(): - await test_list_grpc_routes_async(request_type=dict) - - -def test_list_grpc_routes_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.ListGrpcRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - call.return_value = grpc_route.ListGrpcRoutesResponse() - client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_grpc_routes_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.ListGrpcRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse()) - await client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_grpc_routes_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.ListGrpcRoutesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_grpc_routes( - 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_grpc_routes_flattened_error(): - client = NetworkServicesClient( - 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_grpc_routes( - grpc_route.ListGrpcRoutesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_grpc_routes_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.ListGrpcRoutesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.ListGrpcRoutesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_grpc_routes( - 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_grpc_routes_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_grpc_routes( - grpc_route.ListGrpcRoutesRequest(), - parent='parent_value', - ) - - -def test_list_grpc_routes_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_grpc_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - next_page_token='abc', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[], - next_page_token='def', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - ], - next_page_token='ghi', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_grpc_routes(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grpc_route.GrpcRoute) - for i in results) -def test_list_grpc_routes_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_grpc_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - next_page_token='abc', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[], - next_page_token='def', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - ], - next_page_token='ghi', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - ), - RuntimeError, - ) - pages = list(client.list_grpc_routes(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_grpc_routes_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - next_page_token='abc', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[], - next_page_token='def', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - ], - next_page_token='ghi', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_grpc_routes(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, grpc_route.GrpcRoute) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_grpc_routes_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_grpc_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - next_page_token='abc', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[], - next_page_token='def', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - ], - next_page_token='ghi', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - ), - 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_grpc_routes(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", [ - grpc_route.GetGrpcRouteRequest, - dict, -]) -def test_get_grpc_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.GrpcRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - response = client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grpc_route.GetGrpcRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grpc_route.GrpcRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -def test_get_grpc_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.GetGrpcRouteRequest() - - -def test_get_grpc_route_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 = NetworkServicesClient( - 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 = grpc_route.GetGrpcRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_grpc_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.GetGrpcRouteRequest( - name='name_value', - ) - -def test_get_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - request = {} - client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_grpc_route(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_grpc_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.GetGrpcRouteRequest() - -@pytest.mark.asyncio -async def test_get_grpc_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_grpc_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_grpc_route] = mock_object - - request = {} - await client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_grpc_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_grpc_route_async(transport: str = 'grpc_asyncio', request_type=grpc_route.GetGrpcRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grpc_route.GetGrpcRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grpc_route.GrpcRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -@pytest.mark.asyncio -async def test_get_grpc_route_async_from_dict(): - await test_get_grpc_route_async(request_type=dict) - - -def test_get_grpc_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.GetGrpcRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - call.return_value = grpc_route.GrpcRoute() - client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_grpc_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.GetGrpcRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute()) - await client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_grpc_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.GrpcRoute() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_grpc_route( - 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_grpc_route_flattened_error(): - client = NetworkServicesClient( - 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_grpc_route( - grpc_route.GetGrpcRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_grpc_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_route.GrpcRoute() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grpc_route.GrpcRoute()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_grpc_route( - 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_grpc_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_grpc_route( - grpc_route.GetGrpcRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_grpc_route.CreateGrpcRouteRequest, - dict, -]) -def test_create_grpc_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_grpc_route.CreateGrpcRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_grpc_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest() - - -def test_create_grpc_route_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 = NetworkServicesClient( - 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_grpc_route.CreateGrpcRouteRequest( - parent='parent_value', - grpc_route_id='grpc_route_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_grpc_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest( - parent='parent_value', - grpc_route_id='grpc_route_id_value', - ) - -def test_create_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - request = {} - client.create_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__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_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.CreateGrpcRouteRequest() - -@pytest.mark.asyncio -async def test_create_grpc_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_grpc_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_grpc_route] = mock_object - - request = {} - await client.create_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_grpc_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_grpc_route_async(transport: str = 'grpc_asyncio', request_type=gcn_grpc_route.CreateGrpcRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__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_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_grpc_route.CreateGrpcRouteRequest() - 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_grpc_route_async_from_dict(): - await test_create_grpc_route_async(request_type=dict) - - -def test_create_grpc_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_grpc_route.CreateGrpcRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_grpc_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_grpc_route.CreateGrpcRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_grpc_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__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_grpc_route( - parent='parent_value', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_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].grpc_route - mock_val = gcn_grpc_route.GrpcRoute(name='name_value') - assert arg == mock_val - arg = args[0].grpc_route_id - mock_val = 'grpc_route_id_value' - assert arg == mock_val - - -def test_create_grpc_route_flattened_error(): - client = NetworkServicesClient( - 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_grpc_route( - gcn_grpc_route.CreateGrpcRouteRequest(), - parent='parent_value', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_id_value', - ) - -@pytest.mark.asyncio -async def test_create_grpc_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_grpc_route), - '__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_grpc_route( - parent='parent_value', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_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].grpc_route - mock_val = gcn_grpc_route.GrpcRoute(name='name_value') - assert arg == mock_val - arg = args[0].grpc_route_id - mock_val = 'grpc_route_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_grpc_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_grpc_route( - gcn_grpc_route.CreateGrpcRouteRequest(), - parent='parent_value', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_grpc_route.UpdateGrpcRouteRequest, - dict, -]) -def test_update_grpc_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_grpc_route.UpdateGrpcRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_grpc_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest() - - -def test_update_grpc_route_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 = NetworkServicesClient( - 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_grpc_route.UpdateGrpcRouteRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_grpc_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest( - ) - -def test_update_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - request = {} - client.update_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__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_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_grpc_route.UpdateGrpcRouteRequest() - -@pytest.mark.asyncio -async def test_update_grpc_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_grpc_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_grpc_route] = mock_object - - request = {} - await client.update_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_grpc_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_grpc_route_async(transport: str = 'grpc_asyncio', request_type=gcn_grpc_route.UpdateGrpcRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__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_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_grpc_route.UpdateGrpcRouteRequest() - 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_grpc_route_async_from_dict(): - await test_update_grpc_route_async(request_type=dict) - - -def test_update_grpc_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_grpc_route.UpdateGrpcRouteRequest() - - request.grpc_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'grpc_route.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_grpc_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_grpc_route.UpdateGrpcRouteRequest() - - request.grpc_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'grpc_route.name=name_value', - ) in kw['metadata'] - - -def test_update_grpc_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__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_grpc_route( - grpc_route=gcn_grpc_route.GrpcRoute(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].grpc_route - mock_val = gcn_grpc_route.GrpcRoute(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_grpc_route_flattened_error(): - client = NetworkServicesClient( - 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_grpc_route( - gcn_grpc_route.UpdateGrpcRouteRequest(), - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_grpc_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_grpc_route), - '__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_grpc_route( - grpc_route=gcn_grpc_route.GrpcRoute(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].grpc_route - mock_val = gcn_grpc_route.GrpcRoute(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_grpc_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_grpc_route( - gcn_grpc_route.UpdateGrpcRouteRequest(), - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - grpc_route.DeleteGrpcRouteRequest, - dict, -]) -def test_delete_grpc_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grpc_route.DeleteGrpcRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_grpc_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.DeleteGrpcRouteRequest() - - -def test_delete_grpc_route_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 = NetworkServicesClient( - 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 = grpc_route.DeleteGrpcRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_grpc_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.DeleteGrpcRouteRequest( - name='name_value', - ) - -def test_delete_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - request = {} - client.delete_grpc_route(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_grpc_route(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_grpc_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__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_grpc_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grpc_route.DeleteGrpcRouteRequest() - -@pytest.mark.asyncio -async def test_delete_grpc_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_grpc_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_grpc_route] = mock_object - - request = {} - await client.delete_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_grpc_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_grpc_route_async(transport: str = 'grpc_asyncio', request_type=grpc_route.DeleteGrpcRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_grpc_route), - '__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_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grpc_route.DeleteGrpcRouteRequest() - 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_grpc_route_async_from_dict(): - await test_delete_grpc_route_async(request_type=dict) - - -def test_delete_grpc_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.DeleteGrpcRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_grpc_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grpc_route.DeleteGrpcRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_grpc_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__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_grpc_route( - 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_grpc_route_flattened_error(): - client = NetworkServicesClient( - 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_grpc_route( - grpc_route.DeleteGrpcRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_grpc_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_grpc_route), - '__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_grpc_route( - 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_grpc_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_grpc_route( - grpc_route.DeleteGrpcRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - http_route.ListHttpRoutesRequest, - dict, -]) -def test_list_http_routes(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.ListHttpRoutesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = http_route.ListHttpRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHttpRoutesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_http_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_http_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.ListHttpRoutesRequest() - - -def test_list_http_routes_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 = NetworkServicesClient( - 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 = http_route.ListHttpRoutesRequest( - 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_http_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_http_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.ListHttpRoutesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_http_routes_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 = NetworkServicesClient( - 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_http_routes 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_http_routes] = mock_rpc - request = {} - client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_http_routes(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_http_routes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_http_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.ListHttpRoutesRequest() - -@pytest.mark.asyncio -async def test_list_http_routes_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_http_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_http_routes] = mock_object - - request = {} - await client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_http_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_http_routes_async(transport: str = 'grpc_asyncio', request_type=http_route.ListHttpRoutesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = http_route.ListHttpRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHttpRoutesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_http_routes_async_from_dict(): - await test_list_http_routes_async(request_type=dict) - - -def test_list_http_routes_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.ListHttpRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - call.return_value = http_route.ListHttpRoutesResponse() - client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_http_routes_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.ListHttpRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse()) - await client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_http_routes_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.ListHttpRoutesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_http_routes( - 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_http_routes_flattened_error(): - client = NetworkServicesClient( - 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_http_routes( - http_route.ListHttpRoutesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_http_routes_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.ListHttpRoutesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.ListHttpRoutesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_http_routes( - 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_http_routes_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_http_routes( - http_route.ListHttpRoutesRequest(), - parent='parent_value', - ) - - -def test_list_http_routes_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_http_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - next_page_token='abc', - ), - http_route.ListHttpRoutesResponse( - http_routes=[], - next_page_token='def', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - ], - next_page_token='ghi', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_http_routes(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, http_route.HttpRoute) - for i in results) -def test_list_http_routes_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_http_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - next_page_token='abc', - ), - http_route.ListHttpRoutesResponse( - http_routes=[], - next_page_token='def', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - ], - next_page_token='ghi', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - ), - RuntimeError, - ) - pages = list(client.list_http_routes(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_http_routes_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - next_page_token='abc', - ), - http_route.ListHttpRoutesResponse( - http_routes=[], - next_page_token='def', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - ], - next_page_token='ghi', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_http_routes(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, http_route.HttpRoute) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_http_routes_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_http_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - next_page_token='abc', - ), - http_route.ListHttpRoutesResponse( - http_routes=[], - next_page_token='def', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - ], - next_page_token='ghi', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - ), - 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_http_routes(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", [ - http_route.GetHttpRouteRequest, - dict, -]) -def test_get_http_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.HttpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - response = client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = http_route.GetHttpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, http_route.HttpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -def test_get_http_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.GetHttpRouteRequest() - - -def test_get_http_route_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 = NetworkServicesClient( - 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 = http_route.GetHttpRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_http_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.GetHttpRouteRequest( - name='name_value', - ) - -def test_get_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - request = {} - client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_http_route(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_http_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.GetHttpRouteRequest() - -@pytest.mark.asyncio -async def test_get_http_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_http_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_http_route] = mock_object - - request = {} - await client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_http_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_http_route_async(transport: str = 'grpc_asyncio', request_type=http_route.GetHttpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = http_route.GetHttpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, http_route.HttpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -@pytest.mark.asyncio -async def test_get_http_route_async_from_dict(): - await test_get_http_route_async(request_type=dict) - - -def test_get_http_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.GetHttpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - call.return_value = http_route.HttpRoute() - client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_http_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.GetHttpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute()) - await client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_http_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.HttpRoute() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_http_route( - 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_http_route_flattened_error(): - client = NetworkServicesClient( - 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_http_route( - http_route.GetHttpRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_http_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = http_route.HttpRoute() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(http_route.HttpRoute()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_http_route( - 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_http_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_http_route( - http_route.GetHttpRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_http_route.CreateHttpRouteRequest, - dict, -]) -def test_create_http_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_http_route.CreateHttpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_http_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.CreateHttpRouteRequest() - - -def test_create_http_route_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 = NetworkServicesClient( - 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_http_route.CreateHttpRouteRequest( - parent='parent_value', - http_route_id='http_route_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_http_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.CreateHttpRouteRequest( - parent='parent_value', - http_route_id='http_route_id_value', - ) - -def test_create_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - request = {} - client.create_http_route(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_http_route(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_http_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__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_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.CreateHttpRouteRequest() - -@pytest.mark.asyncio -async def test_create_http_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_http_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_http_route] = mock_object - - request = {} - await client.create_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_http_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_http_route_async(transport: str = 'grpc_asyncio', request_type=gcn_http_route.CreateHttpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__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_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_http_route.CreateHttpRouteRequest() - 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_http_route_async_from_dict(): - await test_create_http_route_async(request_type=dict) - - -def test_create_http_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_http_route.CreateHttpRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_http_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_http_route.CreateHttpRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_http_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__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_http_route( - parent='parent_value', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_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].http_route - mock_val = gcn_http_route.HttpRoute(name='name_value') - assert arg == mock_val - arg = args[0].http_route_id - mock_val = 'http_route_id_value' - assert arg == mock_val - - -def test_create_http_route_flattened_error(): - client = NetworkServicesClient( - 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_http_route( - gcn_http_route.CreateHttpRouteRequest(), - parent='parent_value', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_id_value', - ) - -@pytest.mark.asyncio -async def test_create_http_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_http_route), - '__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_http_route( - parent='parent_value', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_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].http_route - mock_val = gcn_http_route.HttpRoute(name='name_value') - assert arg == mock_val - arg = args[0].http_route_id - mock_val = 'http_route_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_http_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_http_route( - gcn_http_route.CreateHttpRouteRequest(), - parent='parent_value', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_http_route.UpdateHttpRouteRequest, - dict, -]) -def test_update_http_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_http_route.UpdateHttpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_http_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.UpdateHttpRouteRequest() - - -def test_update_http_route_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 = NetworkServicesClient( - 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_http_route.UpdateHttpRouteRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_http_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.UpdateHttpRouteRequest( - ) - -def test_update_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - request = {} - client.update_http_route(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_http_route(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_http_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__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_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_http_route.UpdateHttpRouteRequest() - -@pytest.mark.asyncio -async def test_update_http_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_http_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_http_route] = mock_object - - request = {} - await client.update_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_http_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_http_route_async(transport: str = 'grpc_asyncio', request_type=gcn_http_route.UpdateHttpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__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_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_http_route.UpdateHttpRouteRequest() - 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_http_route_async_from_dict(): - await test_update_http_route_async(request_type=dict) - - -def test_update_http_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_http_route.UpdateHttpRouteRequest() - - request.http_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'http_route.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_http_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_http_route.UpdateHttpRouteRequest() - - request.http_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'http_route.name=name_value', - ) in kw['metadata'] - - -def test_update_http_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__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_http_route( - http_route=gcn_http_route.HttpRoute(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].http_route - mock_val = gcn_http_route.HttpRoute(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_http_route_flattened_error(): - client = NetworkServicesClient( - 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_http_route( - gcn_http_route.UpdateHttpRouteRequest(), - http_route=gcn_http_route.HttpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_http_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_http_route), - '__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_http_route( - http_route=gcn_http_route.HttpRoute(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].http_route - mock_val = gcn_http_route.HttpRoute(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_http_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_http_route( - gcn_http_route.UpdateHttpRouteRequest(), - http_route=gcn_http_route.HttpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - http_route.DeleteHttpRouteRequest, - dict, -]) -def test_delete_http_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = http_route.DeleteHttpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_http_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.DeleteHttpRouteRequest() - - -def test_delete_http_route_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 = NetworkServicesClient( - 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 = http_route.DeleteHttpRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_http_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.DeleteHttpRouteRequest( - name='name_value', - ) - -def test_delete_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - request = {} - client.delete_http_route(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_http_route(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_http_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__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_http_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == http_route.DeleteHttpRouteRequest() - -@pytest.mark.asyncio -async def test_delete_http_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_http_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_http_route] = mock_object - - request = {} - await client.delete_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_http_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_http_route_async(transport: str = 'grpc_asyncio', request_type=http_route.DeleteHttpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_http_route), - '__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_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = http_route.DeleteHttpRouteRequest() - 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_http_route_async_from_dict(): - await test_delete_http_route_async(request_type=dict) - - -def test_delete_http_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.DeleteHttpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_http_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = http_route.DeleteHttpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_http_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__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_http_route( - 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_http_route_flattened_error(): - client = NetworkServicesClient( - 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_http_route( - http_route.DeleteHttpRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_http_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_http_route), - '__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_http_route( - 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_http_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_http_route( - http_route.DeleteHttpRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - tcp_route.ListTcpRoutesRequest, - dict, -]) -def test_list_tcp_routes(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.ListTcpRoutesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tcp_route.ListTcpRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTcpRoutesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tcp_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tcp_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.ListTcpRoutesRequest() - - -def test_list_tcp_routes_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 = NetworkServicesClient( - 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 = tcp_route.ListTcpRoutesRequest( - 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_tcp_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tcp_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.ListTcpRoutesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_tcp_routes_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 = NetworkServicesClient( - 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_tcp_routes 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_tcp_routes] = mock_rpc - request = {} - client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tcp_routes(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_tcp_routes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tcp_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.ListTcpRoutesRequest() - -@pytest.mark.asyncio -async def test_list_tcp_routes_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tcp_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_tcp_routes] = mock_object - - request = {} - await client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_tcp_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_tcp_routes_async(transport: str = 'grpc_asyncio', request_type=tcp_route.ListTcpRoutesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tcp_route.ListTcpRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTcpRoutesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tcp_routes_async_from_dict(): - await test_list_tcp_routes_async(request_type=dict) - - -def test_list_tcp_routes_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.ListTcpRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - call.return_value = tcp_route.ListTcpRoutesResponse() - client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tcp_routes_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.ListTcpRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse()) - await client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_tcp_routes_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.ListTcpRoutesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tcp_routes( - 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_tcp_routes_flattened_error(): - client = NetworkServicesClient( - 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_tcp_routes( - tcp_route.ListTcpRoutesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tcp_routes_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.ListTcpRoutesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.ListTcpRoutesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tcp_routes( - 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_tcp_routes_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tcp_routes( - tcp_route.ListTcpRoutesRequest(), - parent='parent_value', - ) - - -def test_list_tcp_routes_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_tcp_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - next_page_token='abc', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[], - next_page_token='def', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - ], - next_page_token='ghi', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_tcp_routes(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tcp_route.TcpRoute) - for i in results) -def test_list_tcp_routes_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_tcp_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - next_page_token='abc', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[], - next_page_token='def', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - ], - next_page_token='ghi', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tcp_routes(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_tcp_routes_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - next_page_token='abc', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[], - next_page_token='def', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - ], - next_page_token='ghi', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tcp_routes(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, tcp_route.TcpRoute) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tcp_routes_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tcp_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - next_page_token='abc', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[], - next_page_token='def', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - ], - next_page_token='ghi', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - ), - 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_tcp_routes(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", [ - tcp_route.GetTcpRouteRequest, - dict, -]) -def test_get_tcp_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.TcpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - response = client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tcp_route.GetTcpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tcp_route.TcpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -def test_get_tcp_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.GetTcpRouteRequest() - - -def test_get_tcp_route_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 = NetworkServicesClient( - 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 = tcp_route.GetTcpRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_tcp_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.GetTcpRouteRequest( - name='name_value', - ) - -def test_get_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - request = {} - client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_tcp_route(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_tcp_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.GetTcpRouteRequest() - -@pytest.mark.asyncio -async def test_get_tcp_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tcp_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_tcp_route] = mock_object - - request = {} - await client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_tcp_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_tcp_route_async(transport: str = 'grpc_asyncio', request_type=tcp_route.GetTcpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tcp_route.GetTcpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tcp_route.TcpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -@pytest.mark.asyncio -async def test_get_tcp_route_async_from_dict(): - await test_get_tcp_route_async(request_type=dict) - - -def test_get_tcp_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.GetTcpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - call.return_value = tcp_route.TcpRoute() - client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tcp_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.GetTcpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute()) - await client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_tcp_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.TcpRoute() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tcp_route( - 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_tcp_route_flattened_error(): - client = NetworkServicesClient( - 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_tcp_route( - tcp_route.GetTcpRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_tcp_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tcp_route.TcpRoute() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tcp_route.TcpRoute()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tcp_route( - 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_tcp_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_tcp_route( - tcp_route.GetTcpRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tcp_route.CreateTcpRouteRequest, - dict, -]) -def test_create_tcp_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_tcp_route.CreateTcpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_tcp_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.CreateTcpRouteRequest() - - -def test_create_tcp_route_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 = NetworkServicesClient( - 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_tcp_route.CreateTcpRouteRequest( - parent='parent_value', - tcp_route_id='tcp_route_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_tcp_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.CreateTcpRouteRequest( - parent='parent_value', - tcp_route_id='tcp_route_id_value', - ) - -def test_create_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - request = {} - client.create_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__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_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.CreateTcpRouteRequest() - -@pytest.mark.asyncio -async def test_create_tcp_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tcp_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_tcp_route] = mock_object - - request = {} - await client.create_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_tcp_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_tcp_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tcp_route.CreateTcpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__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_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_tcp_route.CreateTcpRouteRequest() - 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_tcp_route_async_from_dict(): - await test_create_tcp_route_async(request_type=dict) - - -def test_create_tcp_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tcp_route.CreateTcpRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tcp_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tcp_route.CreateTcpRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_tcp_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__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_tcp_route( - parent='parent_value', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_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].tcp_route - mock_val = gcn_tcp_route.TcpRoute(name='name_value') - assert arg == mock_val - arg = args[0].tcp_route_id - mock_val = 'tcp_route_id_value' - assert arg == mock_val - - -def test_create_tcp_route_flattened_error(): - client = NetworkServicesClient( - 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_tcp_route( - gcn_tcp_route.CreateTcpRouteRequest(), - parent='parent_value', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_id_value', - ) - -@pytest.mark.asyncio -async def test_create_tcp_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tcp_route), - '__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_tcp_route( - parent='parent_value', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_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].tcp_route - mock_val = gcn_tcp_route.TcpRoute(name='name_value') - assert arg == mock_val - arg = args[0].tcp_route_id - mock_val = 'tcp_route_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_tcp_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_tcp_route( - gcn_tcp_route.CreateTcpRouteRequest(), - parent='parent_value', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tcp_route.UpdateTcpRouteRequest, - dict, -]) -def test_update_tcp_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_tcp_route.UpdateTcpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_tcp_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest() - - -def test_update_tcp_route_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 = NetworkServicesClient( - 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_tcp_route.UpdateTcpRouteRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_tcp_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest( - ) - -def test_update_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - request = {} - client.update_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__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_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tcp_route.UpdateTcpRouteRequest() - -@pytest.mark.asyncio -async def test_update_tcp_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tcp_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_tcp_route] = mock_object - - request = {} - await client.update_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_tcp_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_tcp_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tcp_route.UpdateTcpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__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_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_tcp_route.UpdateTcpRouteRequest() - 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_tcp_route_async_from_dict(): - await test_update_tcp_route_async(request_type=dict) - - -def test_update_tcp_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tcp_route.UpdateTcpRouteRequest() - - request.tcp_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tcp_route.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tcp_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tcp_route.UpdateTcpRouteRequest() - - request.tcp_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tcp_route.name=name_value', - ) in kw['metadata'] - - -def test_update_tcp_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__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_tcp_route( - tcp_route=gcn_tcp_route.TcpRoute(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].tcp_route - mock_val = gcn_tcp_route.TcpRoute(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_tcp_route_flattened_error(): - client = NetworkServicesClient( - 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_tcp_route( - gcn_tcp_route.UpdateTcpRouteRequest(), - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_tcp_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tcp_route), - '__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_tcp_route( - tcp_route=gcn_tcp_route.TcpRoute(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].tcp_route - mock_val = gcn_tcp_route.TcpRoute(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_tcp_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_tcp_route( - gcn_tcp_route.UpdateTcpRouteRequest(), - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - tcp_route.DeleteTcpRouteRequest, - dict, -]) -def test_delete_tcp_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tcp_route.DeleteTcpRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_tcp_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.DeleteTcpRouteRequest() - - -def test_delete_tcp_route_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 = NetworkServicesClient( - 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 = tcp_route.DeleteTcpRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_tcp_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.DeleteTcpRouteRequest( - name='name_value', - ) - -def test_delete_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - request = {} - client.delete_tcp_route(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_tcp_route(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_tcp_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__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_tcp_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tcp_route.DeleteTcpRouteRequest() - -@pytest.mark.asyncio -async def test_delete_tcp_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tcp_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_tcp_route] = mock_object - - request = {} - await client.delete_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_tcp_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_tcp_route_async(transport: str = 'grpc_asyncio', request_type=tcp_route.DeleteTcpRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tcp_route), - '__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_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tcp_route.DeleteTcpRouteRequest() - 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_tcp_route_async_from_dict(): - await test_delete_tcp_route_async(request_type=dict) - - -def test_delete_tcp_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.DeleteTcpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tcp_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tcp_route.DeleteTcpRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_tcp_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__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_tcp_route( - 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_tcp_route_flattened_error(): - client = NetworkServicesClient( - 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_tcp_route( - tcp_route.DeleteTcpRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_tcp_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tcp_route), - '__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_tcp_route( - 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_tcp_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_tcp_route( - tcp_route.DeleteTcpRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - tls_route.ListTlsRoutesRequest, - dict, -]) -def test_list_tls_routes(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.ListTlsRoutesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tls_route.ListTlsRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTlsRoutesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tls_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tls_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.ListTlsRoutesRequest() - - -def test_list_tls_routes_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 = NetworkServicesClient( - 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 = tls_route.ListTlsRoutesRequest( - 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_tls_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tls_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.ListTlsRoutesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_tls_routes_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 = NetworkServicesClient( - 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_tls_routes 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_tls_routes] = mock_rpc - request = {} - client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tls_routes(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_tls_routes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tls_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.ListTlsRoutesRequest() - -@pytest.mark.asyncio -async def test_list_tls_routes_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tls_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_tls_routes] = mock_object - - request = {} - await client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_tls_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_tls_routes_async(transport: str = 'grpc_asyncio', request_type=tls_route.ListTlsRoutesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tls_route.ListTlsRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTlsRoutesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tls_routes_async_from_dict(): - await test_list_tls_routes_async(request_type=dict) - - -def test_list_tls_routes_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.ListTlsRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - call.return_value = tls_route.ListTlsRoutesResponse() - client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tls_routes_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.ListTlsRoutesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse()) - await client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_tls_routes_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.ListTlsRoutesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tls_routes( - 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_tls_routes_flattened_error(): - client = NetworkServicesClient( - 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_tls_routes( - tls_route.ListTlsRoutesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tls_routes_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.ListTlsRoutesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.ListTlsRoutesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tls_routes( - 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_tls_routes_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tls_routes( - tls_route.ListTlsRoutesRequest(), - parent='parent_value', - ) - - -def test_list_tls_routes_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_tls_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - next_page_token='abc', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[], - next_page_token='def', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - ], - next_page_token='ghi', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_tls_routes(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tls_route.TlsRoute) - for i in results) -def test_list_tls_routes_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_tls_routes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - next_page_token='abc', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[], - next_page_token='def', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - ], - next_page_token='ghi', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tls_routes(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_tls_routes_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - next_page_token='abc', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[], - next_page_token='def', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - ], - next_page_token='ghi', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tls_routes(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, tls_route.TlsRoute) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tls_routes_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tls_routes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - next_page_token='abc', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[], - next_page_token='def', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - ], - next_page_token='ghi', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - ), - 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_tls_routes(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", [ - tls_route.GetTlsRouteRequest, - dict, -]) -def test_get_tls_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.TlsRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - response = client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tls_route.GetTlsRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tls_route.TlsRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -def test_get_tls_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.GetTlsRouteRequest() - - -def test_get_tls_route_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 = NetworkServicesClient( - 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 = tls_route.GetTlsRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_tls_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.GetTlsRouteRequest( - name='name_value', - ) - -def test_get_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - request = {} - client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_tls_route(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_tls_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.GetTlsRouteRequest() - -@pytest.mark.asyncio -async def test_get_tls_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tls_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_tls_route] = mock_object - - request = {} - await client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_tls_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_tls_route_async(transport: str = 'grpc_asyncio', request_type=tls_route.GetTlsRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - )) - response = await client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tls_route.GetTlsRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tls_route.TlsRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - - -@pytest.mark.asyncio -async def test_get_tls_route_async_from_dict(): - await test_get_tls_route_async(request_type=dict) - - -def test_get_tls_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.GetTlsRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - call.return_value = tls_route.TlsRoute() - client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tls_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.GetTlsRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute()) - await client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_tls_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.TlsRoute() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tls_route( - 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_tls_route_flattened_error(): - client = NetworkServicesClient( - 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_tls_route( - tls_route.GetTlsRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_tls_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tls_route.TlsRoute() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tls_route.TlsRoute()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tls_route( - 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_tls_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_tls_route( - tls_route.GetTlsRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tls_route.CreateTlsRouteRequest, - dict, -]) -def test_create_tls_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_tls_route.CreateTlsRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_tls_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.CreateTlsRouteRequest() - - -def test_create_tls_route_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 = NetworkServicesClient( - 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_tls_route.CreateTlsRouteRequest( - parent='parent_value', - tls_route_id='tls_route_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_tls_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.CreateTlsRouteRequest( - parent='parent_value', - tls_route_id='tls_route_id_value', - ) - -def test_create_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - request = {} - client.create_tls_route(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_tls_route(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_tls_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__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_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.CreateTlsRouteRequest() - -@pytest.mark.asyncio -async def test_create_tls_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tls_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_tls_route] = mock_object - - request = {} - await client.create_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_tls_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_tls_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tls_route.CreateTlsRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__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_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_tls_route.CreateTlsRouteRequest() - 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_tls_route_async_from_dict(): - await test_create_tls_route_async(request_type=dict) - - -def test_create_tls_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tls_route.CreateTlsRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tls_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tls_route.CreateTlsRouteRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_tls_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__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_tls_route( - parent='parent_value', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_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].tls_route - mock_val = gcn_tls_route.TlsRoute(name='name_value') - assert arg == mock_val - arg = args[0].tls_route_id - mock_val = 'tls_route_id_value' - assert arg == mock_val - - -def test_create_tls_route_flattened_error(): - client = NetworkServicesClient( - 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_tls_route( - gcn_tls_route.CreateTlsRouteRequest(), - parent='parent_value', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_id_value', - ) - -@pytest.mark.asyncio -async def test_create_tls_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tls_route), - '__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_tls_route( - parent='parent_value', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_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].tls_route - mock_val = gcn_tls_route.TlsRoute(name='name_value') - assert arg == mock_val - arg = args[0].tls_route_id - mock_val = 'tls_route_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_tls_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_tls_route( - gcn_tls_route.CreateTlsRouteRequest(), - parent='parent_value', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tls_route.UpdateTlsRouteRequest, - dict, -]) -def test_update_tls_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_tls_route.UpdateTlsRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_tls_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.UpdateTlsRouteRequest() - - -def test_update_tls_route_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 = NetworkServicesClient( - 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_tls_route.UpdateTlsRouteRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_tls_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.UpdateTlsRouteRequest( - ) - -def test_update_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - request = {} - client.update_tls_route(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_tls_route(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_tls_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__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_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_tls_route.UpdateTlsRouteRequest() - -@pytest.mark.asyncio -async def test_update_tls_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tls_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_tls_route] = mock_object - - request = {} - await client.update_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_tls_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_tls_route_async(transport: str = 'grpc_asyncio', request_type=gcn_tls_route.UpdateTlsRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__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_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_tls_route.UpdateTlsRouteRequest() - 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_tls_route_async_from_dict(): - await test_update_tls_route_async(request_type=dict) - - -def test_update_tls_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tls_route.UpdateTlsRouteRequest() - - request.tls_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tls_route.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tls_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_tls_route.UpdateTlsRouteRequest() - - request.tls_route.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tls_route.name=name_value', - ) in kw['metadata'] - - -def test_update_tls_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__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_tls_route( - tls_route=gcn_tls_route.TlsRoute(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].tls_route - mock_val = gcn_tls_route.TlsRoute(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_tls_route_flattened_error(): - client = NetworkServicesClient( - 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_tls_route( - gcn_tls_route.UpdateTlsRouteRequest(), - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_tls_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tls_route), - '__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_tls_route( - tls_route=gcn_tls_route.TlsRoute(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].tls_route - mock_val = gcn_tls_route.TlsRoute(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_tls_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_tls_route( - gcn_tls_route.UpdateTlsRouteRequest(), - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - tls_route.DeleteTlsRouteRequest, - dict, -]) -def test_delete_tls_route(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = tls_route.DeleteTlsRouteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_tls_route_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.DeleteTlsRouteRequest() - - -def test_delete_tls_route_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 = NetworkServicesClient( - 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 = tls_route.DeleteTlsRouteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_tls_route(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.DeleteTlsRouteRequest( - name='name_value', - ) - -def test_delete_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - request = {} - client.delete_tls_route(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_tls_route(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_tls_route_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__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_tls_route() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tls_route.DeleteTlsRouteRequest() - -@pytest.mark.asyncio -async def test_delete_tls_route_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tls_route in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_tls_route] = mock_object - - request = {} - await client.delete_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_tls_route(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_tls_route_async(transport: str = 'grpc_asyncio', request_type=tls_route.DeleteTlsRouteRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tls_route), - '__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_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = tls_route.DeleteTlsRouteRequest() - 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_tls_route_async_from_dict(): - await test_delete_tls_route_async(request_type=dict) - - -def test_delete_tls_route_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.DeleteTlsRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tls_route_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tls_route.DeleteTlsRouteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_tls_route_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__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_tls_route( - 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_tls_route_flattened_error(): - client = NetworkServicesClient( - 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_tls_route( - tls_route.DeleteTlsRouteRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_tls_route_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tls_route), - '__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_tls_route( - 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_tls_route_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_tls_route( - tls_route.DeleteTlsRouteRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service_binding.ListServiceBindingsRequest, - dict, -]) -def test_list_service_bindings(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ListServiceBindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service_binding.ListServiceBindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceBindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_service_bindings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_service_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.ListServiceBindingsRequest() - - -def test_list_service_bindings_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 = NetworkServicesClient( - 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 = service_binding.ListServiceBindingsRequest( - 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_service_bindings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_service_bindings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.ListServiceBindingsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_service_bindings_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 = NetworkServicesClient( - 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_service_bindings 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_service_bindings] = mock_rpc - request = {} - client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_bindings(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_service_bindings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_service_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.ListServiceBindingsRequest() - -@pytest.mark.asyncio -async def test_list_service_bindings_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_service_bindings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_service_bindings] = mock_object - - request = {} - await client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_service_bindings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_service_bindings_async(transport: str = 'grpc_asyncio', request_type=service_binding.ListServiceBindingsRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service_binding.ListServiceBindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceBindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_service_bindings_async_from_dict(): - await test_list_service_bindings_async(request_type=dict) - - -def test_list_service_bindings_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.ListServiceBindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - call.return_value = service_binding.ListServiceBindingsResponse() - client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_service_bindings_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.ListServiceBindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse()) - await client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_service_bindings_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ListServiceBindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_service_bindings( - 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_service_bindings_flattened_error(): - client = NetworkServicesClient( - 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_service_bindings( - service_binding.ListServiceBindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_service_bindings_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ListServiceBindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ListServiceBindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_service_bindings( - 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_service_bindings_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_service_bindings( - service_binding.ListServiceBindingsRequest(), - parent='parent_value', - ) - - -def test_list_service_bindings_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_service_bindings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - next_page_token='abc', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[], - next_page_token='def', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - ], - next_page_token='ghi', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_service_bindings(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service_binding.ServiceBinding) - for i in results) -def test_list_service_bindings_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_service_bindings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - next_page_token='abc', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[], - next_page_token='def', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - ], - next_page_token='ghi', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_service_bindings(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_service_bindings_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - next_page_token='abc', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[], - next_page_token='def', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - ], - next_page_token='ghi', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_service_bindings(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, service_binding.ServiceBinding) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_service_bindings_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_bindings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - next_page_token='abc', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[], - next_page_token='def', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - ], - next_page_token='ghi', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - ), - 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_service_bindings(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", [ - service_binding.GetServiceBindingRequest, - dict, -]) -def test_get_service_binding(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ServiceBinding( - name='name_value', - description='description_value', - service='service_value', - ) - response = client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service_binding.GetServiceBindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_binding.ServiceBinding) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.service == 'service_value' - - -def test_get_service_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.GetServiceBindingRequest() - - -def test_get_service_binding_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 = NetworkServicesClient( - 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 = service_binding.GetServiceBindingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_service_binding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.GetServiceBindingRequest( - name='name_value', - ) - -def test_get_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - request = {} - client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_binding(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_service_binding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding( - name='name_value', - description='description_value', - service='service_value', - )) - response = await client.get_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.GetServiceBindingRequest() - -@pytest.mark.asyncio -async def test_get_service_binding_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_service_binding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_service_binding] = mock_object - - request = {} - await client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_service_binding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_binding_async(transport: str = 'grpc_asyncio', request_type=service_binding.GetServiceBindingRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding( - name='name_value', - description='description_value', - service='service_value', - )) - response = await client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service_binding.GetServiceBindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_binding.ServiceBinding) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.service == 'service_value' - - -@pytest.mark.asyncio -async def test_get_service_binding_async_from_dict(): - await test_get_service_binding_async(request_type=dict) - - -def test_get_service_binding_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.GetServiceBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - call.return_value = service_binding.ServiceBinding() - client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_service_binding_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.GetServiceBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding()) - await client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_service_binding_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ServiceBinding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service_binding( - 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_service_binding_flattened_error(): - client = NetworkServicesClient( - 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_service_binding( - service_binding.GetServiceBindingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_service_binding_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_binding.ServiceBinding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_binding.ServiceBinding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service_binding( - 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_service_binding_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service_binding( - service_binding.GetServiceBindingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_service_binding.CreateServiceBindingRequest, - dict, -]) -def test_create_service_binding(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_service_binding.CreateServiceBindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_service_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_service_binding.CreateServiceBindingRequest() - - -def test_create_service_binding_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 = NetworkServicesClient( - 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_service_binding.CreateServiceBindingRequest( - parent='parent_value', - service_binding_id='service_binding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_service_binding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_service_binding.CreateServiceBindingRequest( - parent='parent_value', - service_binding_id='service_binding_id_value', - ) - -def test_create_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - request = {} - client.create_service_binding(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_service_binding(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_service_binding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__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_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_service_binding.CreateServiceBindingRequest() - -@pytest.mark.asyncio -async def test_create_service_binding_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_service_binding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_service_binding] = mock_object - - request = {} - await client.create_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_service_binding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_binding_async(transport: str = 'grpc_asyncio', request_type=gcn_service_binding.CreateServiceBindingRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__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_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_service_binding.CreateServiceBindingRequest() - 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_service_binding_async_from_dict(): - await test_create_service_binding_async(request_type=dict) - - -def test_create_service_binding_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_service_binding.CreateServiceBindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_service_binding_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_service_binding.CreateServiceBindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_service_binding_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__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_service_binding( - parent='parent_value', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_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].service_binding - mock_val = gcn_service_binding.ServiceBinding(name='name_value') - assert arg == mock_val - arg = args[0].service_binding_id - mock_val = 'service_binding_id_value' - assert arg == mock_val - - -def test_create_service_binding_flattened_error(): - client = NetworkServicesClient( - 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_service_binding( - gcn_service_binding.CreateServiceBindingRequest(), - parent='parent_value', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_id_value', - ) - -@pytest.mark.asyncio -async def test_create_service_binding_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_binding), - '__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_service_binding( - parent='parent_value', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_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].service_binding - mock_val = gcn_service_binding.ServiceBinding(name='name_value') - assert arg == mock_val - arg = args[0].service_binding_id - mock_val = 'service_binding_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_service_binding_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service_binding( - gcn_service_binding.CreateServiceBindingRequest(), - parent='parent_value', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service_binding.DeleteServiceBindingRequest, - dict, -]) -def test_delete_service_binding(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service_binding.DeleteServiceBindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_service_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.DeleteServiceBindingRequest() - - -def test_delete_service_binding_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 = NetworkServicesClient( - 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 = service_binding.DeleteServiceBindingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_service_binding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.DeleteServiceBindingRequest( - name='name_value', - ) - -def test_delete_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - request = {} - client.delete_service_binding(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_service_binding(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_service_binding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__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_service_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_binding.DeleteServiceBindingRequest() - -@pytest.mark.asyncio -async def test_delete_service_binding_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_service_binding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_service_binding] = mock_object - - request = {} - await client.delete_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_service_binding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_service_binding_async(transport: str = 'grpc_asyncio', request_type=service_binding.DeleteServiceBindingRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_binding), - '__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_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service_binding.DeleteServiceBindingRequest() - 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_service_binding_async_from_dict(): - await test_delete_service_binding_async(request_type=dict) - - -def test_delete_service_binding_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.DeleteServiceBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_service_binding_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service_binding.DeleteServiceBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_service_binding_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__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_service_binding( - 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_service_binding_flattened_error(): - client = NetworkServicesClient( - 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_service_binding( - service_binding.DeleteServiceBindingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_service_binding_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service_binding), - '__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_service_binding( - 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_service_binding_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_service_binding( - service_binding.DeleteServiceBindingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - mesh.ListMeshesRequest, - dict, -]) -def test_list_meshes(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_meshes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.ListMeshesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = mesh.ListMeshesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMeshesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_meshes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_meshes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.ListMeshesRequest() - - -def test_list_meshes_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 = NetworkServicesClient( - 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 = mesh.ListMeshesRequest( - 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_meshes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_meshes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.ListMeshesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_meshes_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 = NetworkServicesClient( - 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_meshes 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_meshes] = mock_rpc - request = {} - client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_meshes(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_meshes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_meshes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.ListMeshesRequest() - -@pytest.mark.asyncio -async def test_list_meshes_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_meshes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.list_meshes] = mock_object - - request = {} - await client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_meshes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_meshes_async(transport: str = 'grpc_asyncio', request_type=mesh.ListMeshesRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_meshes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = mesh.ListMeshesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMeshesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_meshes_async_from_dict(): - await test_list_meshes_async(request_type=dict) - - -def test_list_meshes_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.ListMeshesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - call.return_value = mesh.ListMeshesResponse() - client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_meshes_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.ListMeshesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse()) - await client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_meshes_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.ListMeshesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_meshes( - 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_meshes_flattened_error(): - client = NetworkServicesClient( - 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_meshes( - mesh.ListMeshesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_meshes_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.ListMeshesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.ListMeshesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_meshes( - 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_meshes_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_meshes( - mesh.ListMeshesRequest(), - parent='parent_value', - ) - - -def test_list_meshes_pager(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_meshes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - mesh.Mesh(), - ], - next_page_token='abc', - ), - mesh.ListMeshesResponse( - meshes=[], - next_page_token='def', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - ], - next_page_token='ghi', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_meshes(request={}) - - assert pager._metadata == expected_metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mesh.Mesh) - for i in results) -def test_list_meshes_pages(transport_name: str = "grpc"): - client = NetworkServicesClient( - 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_meshes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - mesh.Mesh(), - ], - next_page_token='abc', - ), - mesh.ListMeshesResponse( - meshes=[], - next_page_token='def', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - ], - next_page_token='ghi', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - ], - ), - RuntimeError, - ) - pages = list(client.list_meshes(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_meshes_async_pager(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - mesh.Mesh(), - ], - next_page_token='abc', - ), - mesh.ListMeshesResponse( - meshes=[], - next_page_token='def', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - ], - next_page_token='ghi', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_meshes(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, mesh.Mesh) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_meshes_async_pages(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_meshes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - mesh.Mesh(), - ], - next_page_token='abc', - ), - mesh.ListMeshesResponse( - meshes=[], - next_page_token='def', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - ], - next_page_token='ghi', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - ], - ), - 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_meshes(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", [ - mesh.GetMeshRequest, - dict, -]) -def test_get_mesh(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.Mesh( - name='name_value', - self_link='self_link_value', - description='description_value', - interception_port=1848, - ) - response = client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = mesh.GetMeshRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mesh.Mesh) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.interception_port == 1848 - - -def test_get_mesh_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.GetMeshRequest() - - -def test_get_mesh_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 = NetworkServicesClient( - 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 = mesh.GetMeshRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mesh(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.GetMeshRequest( - name='name_value', - ) - -def test_get_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - request = {} - client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mesh(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_mesh_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh( - name='name_value', - self_link='self_link_value', - description='description_value', - interception_port=1848, - )) - response = await client.get_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.GetMeshRequest() - -@pytest.mark.asyncio -async def test_get_mesh_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_mesh in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.get_mesh] = mock_object - - request = {} - await client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_mesh(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_mesh_async(transport: str = 'grpc_asyncio', request_type=mesh.GetMeshRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh( - name='name_value', - self_link='self_link_value', - description='description_value', - interception_port=1848, - )) - response = await client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = mesh.GetMeshRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mesh.Mesh) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.interception_port == 1848 - - -@pytest.mark.asyncio -async def test_get_mesh_async_from_dict(): - await test_get_mesh_async(request_type=dict) - - -def test_get_mesh_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.GetMeshRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - call.return_value = mesh.Mesh() - client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_mesh_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.GetMeshRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh()) - await client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_mesh_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.Mesh() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_mesh( - 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_mesh_flattened_error(): - client = NetworkServicesClient( - 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_mesh( - mesh.GetMeshRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_mesh_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mesh.Mesh() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mesh.Mesh()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_mesh( - 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_mesh_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_mesh( - mesh.GetMeshRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_mesh.CreateMeshRequest, - dict, -]) -def test_create_mesh(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_mesh.CreateMeshRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_mesh_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.CreateMeshRequest() - - -def test_create_mesh_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 = NetworkServicesClient( - 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_mesh.CreateMeshRequest( - parent='parent_value', - mesh_id='mesh_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mesh(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.CreateMeshRequest( - parent='parent_value', - mesh_id='mesh_id_value', - ) - -def test_create_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - request = {} - client.create_mesh(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_mesh(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_mesh_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__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_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.CreateMeshRequest() - -@pytest.mark.asyncio -async def test_create_mesh_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_mesh in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.create_mesh] = mock_object - - request = {} - await client.create_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_mesh(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_mesh_async(transport: str = 'grpc_asyncio', request_type=gcn_mesh.CreateMeshRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__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_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_mesh.CreateMeshRequest() - 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_mesh_async_from_dict(): - await test_create_mesh_async(request_type=dict) - - -def test_create_mesh_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_mesh.CreateMeshRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_mesh_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_mesh.CreateMeshRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_mesh_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__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_mesh( - parent='parent_value', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_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].mesh - mock_val = gcn_mesh.Mesh(name='name_value') - assert arg == mock_val - arg = args[0].mesh_id - mock_val = 'mesh_id_value' - assert arg == mock_val - - -def test_create_mesh_flattened_error(): - client = NetworkServicesClient( - 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_mesh( - gcn_mesh.CreateMeshRequest(), - parent='parent_value', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_id_value', - ) - -@pytest.mark.asyncio -async def test_create_mesh_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mesh), - '__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_mesh( - parent='parent_value', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_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].mesh - mock_val = gcn_mesh.Mesh(name='name_value') - assert arg == mock_val - arg = args[0].mesh_id - mock_val = 'mesh_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_mesh_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_mesh( - gcn_mesh.CreateMeshRequest(), - parent='parent_value', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_mesh.UpdateMeshRequest, - dict, -]) -def test_update_mesh(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_mesh.UpdateMeshRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_mesh_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.UpdateMeshRequest() - - -def test_update_mesh_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 = NetworkServicesClient( - 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_mesh.UpdateMeshRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mesh(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.UpdateMeshRequest( - ) - -def test_update_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - request = {} - client.update_mesh(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_mesh(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_mesh_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__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_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_mesh.UpdateMeshRequest() - -@pytest.mark.asyncio -async def test_update_mesh_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_mesh in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.update_mesh] = mock_object - - request = {} - await client.update_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_mesh(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_mesh_async(transport: str = 'grpc_asyncio', request_type=gcn_mesh.UpdateMeshRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__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_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_mesh.UpdateMeshRequest() - 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_mesh_async_from_dict(): - await test_update_mesh_async(request_type=dict) - - -def test_update_mesh_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_mesh.UpdateMeshRequest() - - request.mesh.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'mesh.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_mesh_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_mesh.UpdateMeshRequest() - - request.mesh.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'mesh.name=name_value', - ) in kw['metadata'] - - -def test_update_mesh_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__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_mesh( - mesh=gcn_mesh.Mesh(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].mesh - mock_val = gcn_mesh.Mesh(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_mesh_flattened_error(): - client = NetworkServicesClient( - 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_mesh( - gcn_mesh.UpdateMeshRequest(), - mesh=gcn_mesh.Mesh(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_mesh_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mesh), - '__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_mesh( - mesh=gcn_mesh.Mesh(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].mesh - mock_val = gcn_mesh.Mesh(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_mesh_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_mesh( - gcn_mesh.UpdateMeshRequest(), - mesh=gcn_mesh.Mesh(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - mesh.DeleteMeshRequest, - dict, -]) -def test_delete_mesh(request_type, transport: str = 'grpc'): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = mesh.DeleteMeshRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_mesh_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.DeleteMeshRequest() - - -def test_delete_mesh_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 = NetworkServicesClient( - 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 = mesh.DeleteMeshRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mesh(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.DeleteMeshRequest( - name='name_value', - ) - -def test_delete_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - request = {} - client.delete_mesh(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_mesh(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_mesh_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__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_mesh() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == mesh.DeleteMeshRequest() - -@pytest.mark.asyncio -async def test_delete_mesh_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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_mesh in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - class AwaitableMock(mock.AsyncMock): - def __await__(self): - self.await_count += 1 - return iter([]) - mock_object = AwaitableMock() - client._client._transport._wrapped_methods[client._client._transport.delete_mesh] = mock_object - - request = {} - await client.delete_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_mesh(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_mesh_async(transport: str = 'grpc_asyncio', request_type=mesh.DeleteMeshRequest): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mesh), - '__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_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = mesh.DeleteMeshRequest() - 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_mesh_async_from_dict(): - await test_delete_mesh_async(request_type=dict) - - -def test_delete_mesh_field_headers(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.DeleteMeshRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_mesh_field_headers_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = mesh.DeleteMeshRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_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_mesh_flattened(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__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_mesh( - 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_mesh_flattened_error(): - client = NetworkServicesClient( - 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_mesh( - mesh.DeleteMeshRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_mesh_flattened_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mesh), - '__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_mesh( - 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_mesh_flattened_error_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_mesh( - mesh.DeleteMeshRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - endpoint_policy.ListEndpointPoliciesRequest, - dict, -]) -def test_list_endpoint_policies_rest(request_type): - client = NetworkServicesClient( - 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 = endpoint_policy.ListEndpointPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_endpoint_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policies] = mock_rpc - - request = {} - client.list_endpoint_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_endpoint_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_endpoint_policies_rest_required_fields(request_type=endpoint_policy.ListEndpointPoliciesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_endpoint_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_endpoint_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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = endpoint_policy.ListEndpointPoliciesResponse() - # 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 = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_endpoint_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_endpoint_policies_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_endpoint_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_endpoint_policies_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_endpoint_policies") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_endpoint_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = endpoint_policy.ListEndpointPoliciesRequest.pb(endpoint_policy.ListEndpointPoliciesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = endpoint_policy.ListEndpointPoliciesResponse.to_json(endpoint_policy.ListEndpointPoliciesResponse()) - - request = endpoint_policy.ListEndpointPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = endpoint_policy.ListEndpointPoliciesResponse() - - client.list_endpoint_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_endpoint_policies_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.ListEndpointPoliciesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_endpoint_policies(request) - - -def test_list_endpoint_policies_rest_flattened(): - client = NetworkServicesClient( - 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 = endpoint_policy.ListEndpointPoliciesResponse() - - # 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 = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_endpoint_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/*}/endpointPolicies" % client.transport._host, args[1]) - - -def test_list_endpoint_policies_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_endpoint_policies( - endpoint_policy.ListEndpointPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_endpoint_policies_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - next_page_token='abc', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[], - next_page_token='def', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - ], - next_page_token='ghi', - ), - endpoint_policy.ListEndpointPoliciesResponse( - endpoint_policies=[ - endpoint_policy.EndpointPolicy(), - endpoint_policy.EndpointPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(endpoint_policy.ListEndpointPoliciesResponse.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_endpoint_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, endpoint_policy.EndpointPolicy) - for i in results) - - pages = list(client.list_endpoint_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - endpoint_policy.GetEndpointPolicyRequest, - dict, -]) -def test_get_endpoint_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/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 = endpoint_policy.EndpointPolicy( - name='name_value', - type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, - authorization_policy='authorization_policy_value', - description='description_value', - server_tls_policy='server_tls_policy_value', - client_tls_policy='client_tls_policy_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = endpoint_policy.EndpointPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_endpoint_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint_policy.EndpointPolicy) - assert response.name == 'name_value' - assert response.type_ == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY - assert response.authorization_policy == 'authorization_policy_value' - assert response.description == 'description_value' - assert response.server_tls_policy == 'server_tls_policy_value' - assert response.client_tls_policy == 'client_tls_policy_value' - -def test_get_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - - request = {} - client.get_endpoint_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_endpoint_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_endpoint_policy_rest_required_fields(request_type=endpoint_policy.GetEndpointPolicyRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_endpoint_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_endpoint_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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = endpoint_policy.EndpointPolicy() - # 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 = endpoint_policy.EndpointPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_endpoint_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_endpoint_policy_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_endpoint_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_endpoint_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_endpoint_policy") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_endpoint_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = endpoint_policy.GetEndpointPolicyRequest.pb(endpoint_policy.GetEndpointPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = endpoint_policy.EndpointPolicy.to_json(endpoint_policy.EndpointPolicy()) - - request = endpoint_policy.GetEndpointPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = endpoint_policy.EndpointPolicy() - - client.get_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.GetEndpointPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_endpoint_policy(request) - - -def test_get_endpoint_policy_rest_flattened(): - client = NetworkServicesClient( - 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 = endpoint_policy.EndpointPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/endpointPolicies/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 = endpoint_policy.EndpointPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_endpoint_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/*/endpointPolicies/*}" % client.transport._host, args[1]) - - -def test_get_endpoint_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_endpoint_policy( - endpoint_policy.GetEndpointPolicyRequest(), - name='name_value', - ) - - -def test_get_endpoint_policy_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_endpoint_policy.CreateEndpointPolicyRequest, - dict, -]) -def test_create_endpoint_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["endpoint_policy"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'authorization_policy': 'authorization_policy_value', 'endpoint_matcher': {'metadata_label_matcher': {'metadata_label_match_criteria': 1, 'metadata_labels': [{'label_name': 'label_name_value', 'label_value': 'label_value_value'}]}}, 'traffic_port_selector': {'ports': ['ports_value1', 'ports_value2']}, 'description': 'description_value', 'server_tls_policy': 'server_tls_policy_value', 'client_tls_policy': 'client_tls_policy_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_endpoint_policy.CreateEndpointPolicyRequest.meta.fields["endpoint_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["endpoint_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["endpoint_policy"][field])): - del request_init["endpoint_policy"][field][i][subfield] - else: - del request_init["endpoint_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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_endpoint_policy(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - - request = {} - client.create_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["endpoint_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 "endpointPolicyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_endpoint_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "endpointPolicyId" in jsonified_request - assert jsonified_request["endpointPolicyId"] == request_init["endpoint_policy_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["endpointPolicyId"] = 'endpoint_policy_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_endpoint_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("endpoint_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 "endpointPolicyId" in jsonified_request - assert jsonified_request["endpointPolicyId"] == 'endpoint_policy_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_endpoint_policy(request) - - expected_params = [ - ( - "endpointPolicyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_endpoint_policy_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_endpoint_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("endpointPolicyId", )) & set(("parent", "endpointPolicyId", "endpointPolicy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_endpoint_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_endpoint_policy") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_endpoint_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb(gcn_endpoint_policy.CreateEndpointPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_endpoint_policy.CreateEndpointPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_endpoint_policy(request) - - -def test_create_endpoint_policy_rest_flattened(): - client = NetworkServicesClient( - 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', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_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 - - client.create_endpoint_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/*}/endpointPolicies" % client.transport._host, args[1]) - - -def test_create_endpoint_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_endpoint_policy( - gcn_endpoint_policy.CreateEndpointPolicyRequest(), - parent='parent_value', - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - endpoint_policy_id='endpoint_policy_id_value', - ) - - -def test_create_endpoint_policy_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_endpoint_policy.UpdateEndpointPolicyRequest, - dict, -]) -def test_update_endpoint_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} - request_init["endpoint_policy"] = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'authorization_policy': 'authorization_policy_value', 'endpoint_matcher': {'metadata_label_matcher': {'metadata_label_match_criteria': 1, 'metadata_labels': [{'label_name': 'label_name_value', 'label_value': 'label_value_value'}]}}, 'traffic_port_selector': {'ports': ['ports_value1', 'ports_value2']}, 'description': 'description_value', 'server_tls_policy': 'server_tls_policy_value', 'client_tls_policy': 'client_tls_policy_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_endpoint_policy.UpdateEndpointPolicyRequest.meta.fields["endpoint_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["endpoint_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["endpoint_policy"][field])): - del request_init["endpoint_policy"][field][i][subfield] - else: - del request_init["endpoint_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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_endpoint_policy(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - - request = {} - client.update_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_endpoint_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_endpoint_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 = NetworkServicesClient( - 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 - - response = client.update_endpoint_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_endpoint_policy_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_endpoint_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("endpointPolicy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_endpoint_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_endpoint_policy") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_endpoint_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb(gcn_endpoint_policy.UpdateEndpointPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_endpoint_policy(request) - - -def test_update_endpoint_policy_rest_flattened(): - client = NetworkServicesClient( - 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 = {'endpoint_policy': {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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 - - client.update_endpoint_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/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}" % client.transport._host, args[1]) - - -def test_update_endpoint_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_endpoint_policy( - gcn_endpoint_policy.UpdateEndpointPolicyRequest(), - endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_endpoint_policy_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - endpoint_policy.DeleteEndpointPolicyRequest, - dict, -]) -def test_delete_endpoint_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_endpoint_policy(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_endpoint_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 = NetworkServicesClient( - 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_endpoint_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_endpoint_policy] = mock_rpc - - request = {} - client.delete_endpoint_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_endpoint_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_endpoint_policy_rest_required_fields(request_type=endpoint_policy.DeleteEndpointPolicyRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_endpoint_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_endpoint_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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_endpoint_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_endpoint_policy_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_endpoint_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_endpoint_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_endpoint_policy") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_endpoint_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = endpoint_policy.DeleteEndpointPolicyRequest.pb(endpoint_policy.DeleteEndpointPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = endpoint_policy.DeleteEndpointPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_endpoint_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_endpoint_policy_rest_bad_request(transport: str = 'rest', request_type=endpoint_policy.DeleteEndpointPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/endpointPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_endpoint_policy(request) - - -def test_delete_endpoint_policy_rest_flattened(): - client = NetworkServicesClient( - 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/endpointPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_endpoint_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/*/endpointPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_endpoint_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_endpoint_policy( - endpoint_policy.DeleteEndpointPolicyRequest(), - name='name_value', - ) - - -def test_delete_endpoint_policy_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gateway.ListGatewaysRequest, - dict, -]) -def test_list_gateways_rest(request_type): - client = NetworkServicesClient( - 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 = gateway.ListGatewaysResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gateway.ListGatewaysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_gateways(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGatewaysPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_gateways_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 = NetworkServicesClient( - 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_gateways 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_gateways] = mock_rpc - - request = {} - client.list_gateways(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_gateways(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_gateways_rest_required_fields(request_type=gateway.ListGatewaysRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_gateways._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_gateways._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gateway.ListGatewaysResponse() - # 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 = gateway.ListGatewaysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_gateways(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_gateways_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_gateways._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_gateways_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_gateways") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_gateways") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gateway.ListGatewaysRequest.pb(gateway.ListGatewaysRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gateway.ListGatewaysResponse.to_json(gateway.ListGatewaysResponse()) - - request = gateway.ListGatewaysRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gateway.ListGatewaysResponse() - - client.list_gateways(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_gateways_rest_bad_request(transport: str = 'rest', request_type=gateway.ListGatewaysRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_gateways(request) - - -def test_list_gateways_rest_flattened(): - client = NetworkServicesClient( - 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 = gateway.ListGatewaysResponse() - - # 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 = gateway.ListGatewaysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_gateways(**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/*}/gateways" % client.transport._host, args[1]) - - -def test_list_gateways_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_gateways( - gateway.ListGatewaysRequest(), - parent='parent_value', - ) - - -def test_list_gateways_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - gateway.Gateway(), - ], - next_page_token='abc', - ), - gateway.ListGatewaysResponse( - gateways=[], - next_page_token='def', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - ], - next_page_token='ghi', - ), - gateway.ListGatewaysResponse( - gateways=[ - gateway.Gateway(), - gateway.Gateway(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(gateway.ListGatewaysResponse.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_gateways(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gateway.Gateway) - for i in results) - - pages = list(client.list_gateways(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gateway.GetGatewayRequest, - dict, -]) -def test_get_gateway_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/gateways/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 = gateway.Gateway( - name='name_value', - self_link='self_link_value', - description='description_value', - type_=gateway.Gateway.Type.OPEN_MESH, - ports=[568], - scope='scope_value', - server_tls_policy='server_tls_policy_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gateway.Gateway.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_gateway(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gateway.Gateway) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.type_ == gateway.Gateway.Type.OPEN_MESH - assert response.ports == [568] - assert response.scope == 'scope_value' - assert response.server_tls_policy == 'server_tls_policy_value' - -def test_get_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - - request = {} - client.get_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_gateway(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_gateway_rest_required_fields(request_type=gateway.GetGatewayRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_gateway._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_gateway._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gateway.Gateway() - # 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 = gateway.Gateway.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_gateway(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_gateway_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_gateway_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_gateway") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gateway.GetGatewayRequest.pb(gateway.GetGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gateway.Gateway.to_json(gateway.Gateway()) - - request = gateway.GetGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gateway.Gateway() - - client.get_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_gateway_rest_bad_request(transport: str = 'rest', request_type=gateway.GetGatewayRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_gateway(request) - - -def test_get_gateway_rest_flattened(): - client = NetworkServicesClient( - 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 = gateway.Gateway() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/gateways/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 = gateway.Gateway.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_gateway(**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/*/gateways/*}" % client.transport._host, args[1]) - - -def test_get_gateway_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_gateway( - gateway.GetGatewayRequest(), - name='name_value', - ) - - -def test_get_gateway_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_gateway.CreateGatewayRequest, - dict, -]) -def test_create_gateway_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["gateway"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'type_': 1, 'ports': [569, 570], 'scope': 'scope_value', 'server_tls_policy': 'server_tls_policy_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_gateway.CreateGatewayRequest.meta.fields["gateway"] - - 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["gateway"].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["gateway"][field])): - del request_init["gateway"][field][i][subfield] - else: - del request_init["gateway"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_gateway(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - - request = {} - client.create_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gcn_gateway.CreateGatewayRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["gateway_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 "gatewayId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_gateway._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "gatewayId" in jsonified_request - assert jsonified_request["gatewayId"] == request_init["gateway_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["gatewayId"] = 'gateway_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_gateway._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("gateway_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 "gatewayId" in jsonified_request - assert jsonified_request["gatewayId"] == 'gateway_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_gateway(request) - - expected_params = [ - ( - "gatewayId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_gateway_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(("gatewayId", )) & set(("parent", "gatewayId", "gateway", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_gateway_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_gateway") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_gateway.CreateGatewayRequest.pb(gcn_gateway.CreateGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_gateway.CreateGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_gateway_rest_bad_request(transport: str = 'rest', request_type=gcn_gateway.CreateGatewayRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_gateway(request) - - -def test_create_gateway_rest_flattened(): - client = NetworkServicesClient( - 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', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_gateway(**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/*}/gateways" % client.transport._host, args[1]) - - -def test_create_gateway_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_gateway( - gcn_gateway.CreateGatewayRequest(), - parent='parent_value', - gateway=gcn_gateway.Gateway(name='name_value'), - gateway_id='gateway_id_value', - ) - - -def test_create_gateway_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_gateway.UpdateGatewayRequest, - dict, -]) -def test_update_gateway_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} - request_init["gateway"] = {'name': 'projects/sample1/locations/sample2/gateways/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'type_': 1, 'ports': [569, 570], 'scope': 'scope_value', 'server_tls_policy': 'server_tls_policy_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_gateway.UpdateGatewayRequest.meta.fields["gateway"] - - 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["gateway"].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["gateway"][field])): - del request_init["gateway"][field][i][subfield] - else: - del request_init["gateway"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_gateway(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - - request = {} - client.update_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gcn_gateway.UpdateGatewayRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_gateway._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_gateway._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 = NetworkServicesClient( - 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 - - response = client.update_gateway(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_gateway_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("gateway", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_gateway_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_gateway") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_gateway.UpdateGatewayRequest.pb(gcn_gateway.UpdateGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_gateway.UpdateGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_gateway_rest_bad_request(transport: str = 'rest', request_type=gcn_gateway.UpdateGatewayRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_gateway(request) - - -def test_update_gateway_rest_flattened(): - client = NetworkServicesClient( - 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 = {'gateway': {'name': 'projects/sample1/locations/sample2/gateways/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - gateway=gcn_gateway.Gateway(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 - - client.update_gateway(**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/{gateway.name=projects/*/locations/*/gateways/*}" % client.transport._host, args[1]) - - -def test_update_gateway_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_gateway( - gcn_gateway.UpdateGatewayRequest(), - gateway=gcn_gateway.Gateway(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_gateway_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gateway.DeleteGatewayRequest, - dict, -]) -def test_delete_gateway_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_gateway(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_gateway_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 = NetworkServicesClient( - 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_gateway 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_gateway] = mock_rpc - - request = {} - client.delete_gateway(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_gateway(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_gateway_rest_required_fields(request_type=gateway.DeleteGatewayRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_gateway._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_gateway._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_gateway(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_gateway_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_gateway_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_gateway") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gateway.DeleteGatewayRequest.pb(gateway.DeleteGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gateway.DeleteGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_gateway_rest_bad_request(transport: str = 'rest', request_type=gateway.DeleteGatewayRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/gateways/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_gateway(request) - - -def test_delete_gateway_rest_flattened(): - client = NetworkServicesClient( - 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/gateways/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_gateway(**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/*/gateways/*}" % client.transport._host, args[1]) - - -def test_delete_gateway_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_gateway( - gateway.DeleteGatewayRequest(), - name='name_value', - ) - - -def test_delete_gateway_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - grpc_route.ListGrpcRoutesRequest, - dict, -]) -def test_list_grpc_routes_rest(request_type): - client = NetworkServicesClient( - 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 = grpc_route.ListGrpcRoutesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grpc_route.ListGrpcRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_grpc_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGrpcRoutesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_grpc_routes_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 = NetworkServicesClient( - 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_grpc_routes 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_grpc_routes] = mock_rpc - - request = {} - client.list_grpc_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_grpc_routes(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_grpc_routes_rest_required_fields(request_type=grpc_route.ListGrpcRoutesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_grpc_routes._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_grpc_routes._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grpc_route.ListGrpcRoutesResponse() - # 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 = grpc_route.ListGrpcRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_grpc_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_grpc_routes_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_grpc_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_grpc_routes_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_grpc_routes") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_grpc_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grpc_route.ListGrpcRoutesRequest.pb(grpc_route.ListGrpcRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = grpc_route.ListGrpcRoutesResponse.to_json(grpc_route.ListGrpcRoutesResponse()) - - request = grpc_route.ListGrpcRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grpc_route.ListGrpcRoutesResponse() - - client.list_grpc_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_grpc_routes_rest_bad_request(transport: str = 'rest', request_type=grpc_route.ListGrpcRoutesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_grpc_routes(request) - - -def test_list_grpc_routes_rest_flattened(): - client = NetworkServicesClient( - 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 = grpc_route.ListGrpcRoutesResponse() - - # 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 = grpc_route.ListGrpcRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_grpc_routes(**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/*}/grpcRoutes" % client.transport._host, args[1]) - - -def test_list_grpc_routes_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_grpc_routes( - grpc_route.ListGrpcRoutesRequest(), - parent='parent_value', - ) - - -def test_list_grpc_routes_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - next_page_token='abc', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[], - next_page_token='def', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - ], - next_page_token='ghi', - ), - grpc_route.ListGrpcRoutesResponse( - grpc_routes=[ - grpc_route.GrpcRoute(), - grpc_route.GrpcRoute(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grpc_route.ListGrpcRoutesResponse.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_grpc_routes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grpc_route.GrpcRoute) - for i in results) - - pages = list(client.list_grpc_routes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - grpc_route.GetGrpcRouteRequest, - dict, -]) -def test_get_grpc_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grpc_route.GrpcRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_grpc_route(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grpc_route.GrpcRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - -def test_get_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - - request = {} - client.get_grpc_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_grpc_route(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_grpc_route_rest_required_fields(request_type=grpc_route.GetGrpcRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grpc_route.GrpcRoute() - # 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 = grpc_route.GrpcRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_grpc_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_grpc_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_grpc_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_grpc_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_grpc_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_grpc_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grpc_route.GetGrpcRouteRequest.pb(grpc_route.GetGrpcRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = grpc_route.GrpcRoute.to_json(grpc_route.GrpcRoute()) - - request = grpc_route.GetGrpcRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grpc_route.GrpcRoute() - - client.get_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_grpc_route_rest_bad_request(transport: str = 'rest', request_type=grpc_route.GetGrpcRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_grpc_route(request) - - -def test_get_grpc_route_rest_flattened(): - client = NetworkServicesClient( - 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 = grpc_route.GrpcRoute() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, args[1]) - - -def test_get_grpc_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_grpc_route( - grpc_route.GetGrpcRouteRequest(), - name='name_value', - ) - - -def test_get_grpc_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_grpc_route.CreateGrpcRouteRequest, - dict, -]) -def test_create_grpc_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["grpc_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'rules': [{'matches': [{'method': {'type_': 1, 'grpc_service': 'grpc_service_value', 'grpc_method': 'grpc_method_value', 'case_sensitive': True}, 'headers': [{'type_': 1, 'key': 'key_value', 'value': 'value_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197}}}]} - # 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_grpc_route.CreateGrpcRouteRequest.meta.fields["grpc_route"] - - 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["grpc_route"].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["grpc_route"][field])): - del request_init["grpc_route"][field][i][subfield] - else: - del request_init["grpc_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_grpc_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - - request = {} - client.create_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=gcn_grpc_route.CreateGrpcRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["grpc_route_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 "grpcRouteId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_grpc_route._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "grpcRouteId" in jsonified_request - assert jsonified_request["grpcRouteId"] == request_init["grpc_route_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["grpcRouteId"] = 'grpc_route_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_grpc_route._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("grpc_route_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 "grpcRouteId" in jsonified_request - assert jsonified_request["grpcRouteId"] == 'grpc_route_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_grpc_route(request) - - expected_params = [ - ( - "grpcRouteId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_grpc_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_grpc_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("grpcRouteId", )) & set(("parent", "grpcRouteId", "grpcRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_grpc_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_grpc_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_grpc_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_grpc_route.CreateGrpcRouteRequest.pb(gcn_grpc_route.CreateGrpcRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_grpc_route.CreateGrpcRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_grpc_route_rest_bad_request(transport: str = 'rest', request_type=gcn_grpc_route.CreateGrpcRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_grpc_route(request) - - -def test_create_grpc_route_rest_flattened(): - client = NetworkServicesClient( - 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', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_grpc_route(**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/*}/grpcRoutes" % client.transport._host, args[1]) - - -def test_create_grpc_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_grpc_route( - gcn_grpc_route.CreateGrpcRouteRequest(), - parent='parent_value', - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - grpc_route_id='grpc_route_id_value', - ) - - -def test_create_grpc_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_grpc_route.UpdateGrpcRouteRequest, - dict, -]) -def test_update_grpc_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} - request_init["grpc_route"] = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'rules': [{'matches': [{'method': {'type_': 1, 'grpc_service': 'grpc_service_value', 'grpc_method': 'grpc_method_value', 'case_sensitive': True}, 'headers': [{'type_': 1, 'key': 'key_value', 'value': 'value_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197}}}]} - # 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_grpc_route.UpdateGrpcRouteRequest.meta.fields["grpc_route"] - - 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["grpc_route"].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["grpc_route"][field])): - del request_init["grpc_route"][field][i][subfield] - else: - del request_init["grpc_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_grpc_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - - request = {} - client.update_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=gcn_grpc_route.UpdateGrpcRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( - 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 - - response = client.update_grpc_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_grpc_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_grpc_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("grpcRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_grpc_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_grpc_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_grpc_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_grpc_route.UpdateGrpcRouteRequest.pb(gcn_grpc_route.UpdateGrpcRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_grpc_route.UpdateGrpcRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_grpc_route_rest_bad_request(transport: str = 'rest', request_type=gcn_grpc_route.UpdateGrpcRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_grpc_route(request) - - -def test_update_grpc_route_rest_flattened(): - client = NetworkServicesClient( - 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 = {'grpc_route': {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - grpc_route=gcn_grpc_route.GrpcRoute(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 - - client.update_grpc_route(**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/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}" % client.transport._host, args[1]) - - -def test_update_grpc_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_grpc_route( - gcn_grpc_route.UpdateGrpcRouteRequest(), - grpc_route=gcn_grpc_route.GrpcRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_grpc_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - grpc_route.DeleteGrpcRouteRequest, - dict, -]) -def test_delete_grpc_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_grpc_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_grpc_route_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 = NetworkServicesClient( - 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_grpc_route 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_grpc_route] = mock_rpc - - request = {} - client.delete_grpc_route(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_grpc_route(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_grpc_route_rest_required_fields(request_type=grpc_route.DeleteGrpcRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_grpc_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_grpc_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_grpc_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_grpc_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_grpc_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_grpc_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = grpc_route.DeleteGrpcRouteRequest.pb(grpc_route.DeleteGrpcRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = grpc_route.DeleteGrpcRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_grpc_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_grpc_route_rest_bad_request(transport: str = 'rest', request_type=grpc_route.DeleteGrpcRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/grpcRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_grpc_route(request) - - -def test_delete_grpc_route_rest_flattened(): - client = NetworkServicesClient( - 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/grpcRoutes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, args[1]) - - -def test_delete_grpc_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_grpc_route( - grpc_route.DeleteGrpcRouteRequest(), - name='name_value', - ) - - -def test_delete_grpc_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - http_route.ListHttpRoutesRequest, - dict, -]) -def test_list_http_routes_rest(request_type): - client = NetworkServicesClient( - 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 = http_route.ListHttpRoutesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = http_route.ListHttpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_http_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHttpRoutesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_http_routes_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 = NetworkServicesClient( - 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_http_routes 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_http_routes] = mock_rpc - - request = {} - client.list_http_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_http_routes(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_http_routes_rest_required_fields(request_type=http_route.ListHttpRoutesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_http_routes._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_http_routes._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = http_route.ListHttpRoutesResponse() - # 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 = http_route.ListHttpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_http_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_http_routes_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_http_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_http_routes_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_http_routes") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_http_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = http_route.ListHttpRoutesRequest.pb(http_route.ListHttpRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = http_route.ListHttpRoutesResponse.to_json(http_route.ListHttpRoutesResponse()) - - request = http_route.ListHttpRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = http_route.ListHttpRoutesResponse() - - client.list_http_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_http_routes_rest_bad_request(transport: str = 'rest', request_type=http_route.ListHttpRoutesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_http_routes(request) - - -def test_list_http_routes_rest_flattened(): - client = NetworkServicesClient( - 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 = http_route.ListHttpRoutesResponse() - - # 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 = http_route.ListHttpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_http_routes(**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/*}/httpRoutes" % client.transport._host, args[1]) - - -def test_list_http_routes_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_http_routes( - http_route.ListHttpRoutesRequest(), - parent='parent_value', - ) - - -def test_list_http_routes_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - next_page_token='abc', - ), - http_route.ListHttpRoutesResponse( - http_routes=[], - next_page_token='def', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - ], - next_page_token='ghi', - ), - http_route.ListHttpRoutesResponse( - http_routes=[ - http_route.HttpRoute(), - http_route.HttpRoute(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(http_route.ListHttpRoutesResponse.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_http_routes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, http_route.HttpRoute) - for i in results) - - pages = list(client.list_http_routes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - http_route.GetHttpRouteRequest, - dict, -]) -def test_get_http_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - hostnames=['hostnames_value'], - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = http_route.HttpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_http_route(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, http_route.HttpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.hostnames == ['hostnames_value'] - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - -def test_get_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - - request = {} - client.get_http_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_http_route(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_http_route_rest_required_fields(request_type=http_route.GetHttpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_http_route._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_http_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = http_route.HttpRoute() - # 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 = http_route.HttpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_http_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_http_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_http_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_http_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_http_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_http_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = http_route.GetHttpRouteRequest.pb(http_route.GetHttpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = http_route.HttpRoute.to_json(http_route.HttpRoute()) - - request = http_route.GetHttpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = http_route.HttpRoute() - - client.get_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_http_route_rest_bad_request(transport: str = 'rest', request_type=http_route.GetHttpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_http_route(request) - - -def test_get_http_route_rest_flattened(): - client = NetworkServicesClient( - 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 = http_route.HttpRoute() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_http_route(**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/*/httpRoutes/*}" % client.transport._host, args[1]) - - -def test_get_http_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_http_route( - http_route.GetHttpRouteRequest(), - name='name_value', - ) - - -def test_get_http_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_http_route.CreateHttpRouteRequest, - dict, -]) -def test_create_http_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["http_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}, 'rules': [{'matches': [{'full_path_match': 'full_path_match_value', 'prefix_match': 'prefix_match_value', 'regex_match': 'regex_match_value', 'ignore_case': True, 'headers': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'prefix_match': 'prefix_match_value', 'present_match': True, 'suffix_match': 'suffix_match_value', 'range_match': {'start': 558, 'end': 311}, 'header': 'header_value', 'invert_match': True}], 'query_parameters': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'present_match': True, 'query_parameter': 'query_parameter_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'redirect': {'host_redirect': 'host_redirect_value', 'path_redirect': 'path_redirect_value', 'prefix_rewrite': 'prefix_rewrite_value', 'response_code': 1, 'https_redirect': True, 'strip_query': True, 'port_redirect': 1398}, 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'request_header_modifier': {'set': {}, 'add': {}, 'remove': ['remove_value1', 'remove_value2']}, 'response_header_modifier': {}, 'url_rewrite': {'path_prefix_rewrite': 'path_prefix_rewrite_value', 'host_rewrite': 'host_rewrite_value'}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197, 'per_try_timeout': {}}, 'request_mirror_policy': {'destination': {}}, 'cors_policy': {'allow_origins': ['allow_origins_value1', 'allow_origins_value2'], 'allow_origin_regexes': ['allow_origin_regexes_value1', 'allow_origin_regexes_value2'], 'allow_methods': ['allow_methods_value1', 'allow_methods_value2'], 'allow_headers': ['allow_headers_value1', 'allow_headers_value2'], 'expose_headers': ['expose_headers_value1', 'expose_headers_value2'], 'max_age': 'max_age_value', 'allow_credentials': True, 'disabled': True}}}]} - # 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_http_route.CreateHttpRouteRequest.meta.fields["http_route"] - - 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["http_route"].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["http_route"][field])): - del request_init["http_route"][field][i][subfield] - else: - del request_init["http_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_http_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - - request = {} - client.create_http_route(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_http_route(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_http_route_rest_required_fields(request_type=gcn_http_route.CreateHttpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["http_route_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 "httpRouteId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_http_route._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "httpRouteId" in jsonified_request - assert jsonified_request["httpRouteId"] == request_init["http_route_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["httpRouteId"] = 'http_route_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_http_route._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("http_route_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 "httpRouteId" in jsonified_request - assert jsonified_request["httpRouteId"] == 'http_route_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_http_route(request) - - expected_params = [ - ( - "httpRouteId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_http_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_http_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("httpRouteId", )) & set(("parent", "httpRouteId", "httpRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_http_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_http_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_http_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_http_route.CreateHttpRouteRequest.pb(gcn_http_route.CreateHttpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_http_route.CreateHttpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_http_route_rest_bad_request(transport: str = 'rest', request_type=gcn_http_route.CreateHttpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_http_route(request) - - -def test_create_http_route_rest_flattened(): - client = NetworkServicesClient( - 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', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_http_route(**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/*}/httpRoutes" % client.transport._host, args[1]) - - -def test_create_http_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_http_route( - gcn_http_route.CreateHttpRouteRequest(), - parent='parent_value', - http_route=gcn_http_route.HttpRoute(name='name_value'), - http_route_id='http_route_id_value', - ) - - -def test_create_http_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_http_route.UpdateHttpRouteRequest, - dict, -]) -def test_update_http_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} - request_init["http_route"] = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3', 'self_link': 'self_link_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'hostnames': ['hostnames_value1', 'hostnames_value2'], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}, 'rules': [{'matches': [{'full_path_match': 'full_path_match_value', 'prefix_match': 'prefix_match_value', 'regex_match': 'regex_match_value', 'ignore_case': True, 'headers': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'prefix_match': 'prefix_match_value', 'present_match': True, 'suffix_match': 'suffix_match_value', 'range_match': {'start': 558, 'end': 311}, 'header': 'header_value', 'invert_match': True}], 'query_parameters': [{'exact_match': 'exact_match_value', 'regex_match': 'regex_match_value', 'present_match': True, 'query_parameter': 'query_parameter_value'}]}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'redirect': {'host_redirect': 'host_redirect_value', 'path_redirect': 'path_redirect_value', 'prefix_rewrite': 'prefix_rewrite_value', 'response_code': 1, 'https_redirect': True, 'strip_query': True, 'port_redirect': 1398}, 'fault_injection_policy': {'delay': {'fixed_delay': {'seconds': 751, 'nanos': 543}, 'percentage': 1054}, 'abort': {'http_status': 1219, 'percentage': 1054}}, 'request_header_modifier': {'set': {}, 'add': {}, 'remove': ['remove_value1', 'remove_value2']}, 'response_header_modifier': {}, 'url_rewrite': {'path_prefix_rewrite': 'path_prefix_rewrite_value', 'host_rewrite': 'host_rewrite_value'}, 'timeout': {}, 'retry_policy': {'retry_conditions': ['retry_conditions_value1', 'retry_conditions_value2'], 'num_retries': 1197, 'per_try_timeout': {}}, 'request_mirror_policy': {'destination': {}}, 'cors_policy': {'allow_origins': ['allow_origins_value1', 'allow_origins_value2'], 'allow_origin_regexes': ['allow_origin_regexes_value1', 'allow_origin_regexes_value2'], 'allow_methods': ['allow_methods_value1', 'allow_methods_value2'], 'allow_headers': ['allow_headers_value1', 'allow_headers_value2'], 'expose_headers': ['expose_headers_value1', 'expose_headers_value2'], 'max_age': 'max_age_value', 'allow_credentials': True, 'disabled': True}}}]} - # 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_http_route.UpdateHttpRouteRequest.meta.fields["http_route"] - - 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["http_route"].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["http_route"][field])): - del request_init["http_route"][field][i][subfield] - else: - del request_init["http_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_http_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - - request = {} - client.update_http_route(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_http_route(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_http_route_rest_required_fields(request_type=gcn_http_route.UpdateHttpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_http_route._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_http_route._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 = NetworkServicesClient( - 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 - - response = client.update_http_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_http_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_http_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("httpRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_http_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_http_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_http_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_http_route.UpdateHttpRouteRequest.pb(gcn_http_route.UpdateHttpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_http_route.UpdateHttpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_http_route_rest_bad_request(transport: str = 'rest', request_type=gcn_http_route.UpdateHttpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_http_route(request) - - -def test_update_http_route_rest_flattened(): - client = NetworkServicesClient( - 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 = {'http_route': {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - http_route=gcn_http_route.HttpRoute(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 - - client.update_http_route(**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/{http_route.name=projects/*/locations/*/httpRoutes/*}" % client.transport._host, args[1]) - - -def test_update_http_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_http_route( - gcn_http_route.UpdateHttpRouteRequest(), - http_route=gcn_http_route.HttpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_http_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - http_route.DeleteHttpRouteRequest, - dict, -]) -def test_delete_http_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_http_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_http_route_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 = NetworkServicesClient( - 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_http_route 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_http_route] = mock_rpc - - request = {} - client.delete_http_route(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_http_route(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_http_route_rest_required_fields(request_type=http_route.DeleteHttpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_http_route._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_http_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_http_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_http_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_http_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_http_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_http_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_http_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = http_route.DeleteHttpRouteRequest.pb(http_route.DeleteHttpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = http_route.DeleteHttpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_http_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_http_route_rest_bad_request(transport: str = 'rest', request_type=http_route.DeleteHttpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/httpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_http_route(request) - - -def test_delete_http_route_rest_flattened(): - client = NetworkServicesClient( - 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/httpRoutes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_http_route(**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/*/httpRoutes/*}" % client.transport._host, args[1]) - - -def test_delete_http_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_http_route( - http_route.DeleteHttpRouteRequest(), - name='name_value', - ) - - -def test_delete_http_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tcp_route.ListTcpRoutesRequest, - dict, -]) -def test_list_tcp_routes_rest(request_type): - client = NetworkServicesClient( - 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 = tcp_route.ListTcpRoutesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tcp_route.ListTcpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tcp_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTcpRoutesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_tcp_routes_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 = NetworkServicesClient( - 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_tcp_routes 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_tcp_routes] = mock_rpc - - request = {} - client.list_tcp_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tcp_routes(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_tcp_routes_rest_required_fields(request_type=tcp_route.ListTcpRoutesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tcp_routes._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_tcp_routes._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tcp_route.ListTcpRoutesResponse() - # 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 = tcp_route.ListTcpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tcp_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tcp_routes_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tcp_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tcp_routes_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tcp_routes") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_tcp_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tcp_route.ListTcpRoutesRequest.pb(tcp_route.ListTcpRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tcp_route.ListTcpRoutesResponse.to_json(tcp_route.ListTcpRoutesResponse()) - - request = tcp_route.ListTcpRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tcp_route.ListTcpRoutesResponse() - - client.list_tcp_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tcp_routes_rest_bad_request(transport: str = 'rest', request_type=tcp_route.ListTcpRoutesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tcp_routes(request) - - -def test_list_tcp_routes_rest_flattened(): - client = NetworkServicesClient( - 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 = tcp_route.ListTcpRoutesResponse() - - # 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 = tcp_route.ListTcpRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tcp_routes(**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/*}/tcpRoutes" % client.transport._host, args[1]) - - -def test_list_tcp_routes_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tcp_routes( - tcp_route.ListTcpRoutesRequest(), - parent='parent_value', - ) - - -def test_list_tcp_routes_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - next_page_token='abc', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[], - next_page_token='def', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - ], - next_page_token='ghi', - ), - tcp_route.ListTcpRoutesResponse( - tcp_routes=[ - tcp_route.TcpRoute(), - tcp_route.TcpRoute(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(tcp_route.ListTcpRoutesResponse.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_tcp_routes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tcp_route.TcpRoute) - for i in results) - - pages = list(client.list_tcp_routes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - tcp_route.GetTcpRouteRequest, - dict, -]) -def test_get_tcp_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tcp_route.TcpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_tcp_route(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tcp_route.TcpRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - -def test_get_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - - request = {} - client.get_tcp_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_tcp_route(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_tcp_route_rest_required_fields(request_type=tcp_route.GetTcpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tcp_route.TcpRoute() - # 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 = tcp_route.TcpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_tcp_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_tcp_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_tcp_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tcp_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tcp_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_tcp_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tcp_route.GetTcpRouteRequest.pb(tcp_route.GetTcpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tcp_route.TcpRoute.to_json(tcp_route.TcpRoute()) - - request = tcp_route.GetTcpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tcp_route.TcpRoute() - - client.get_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tcp_route_rest_bad_request(transport: str = 'rest', request_type=tcp_route.GetTcpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_tcp_route(request) - - -def test_get_tcp_route_rest_flattened(): - client = NetworkServicesClient( - 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 = tcp_route.TcpRoute() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, args[1]) - - -def test_get_tcp_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tcp_route( - tcp_route.GetTcpRouteRequest(), - name='name_value', - ) - - -def test_get_tcp_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tcp_route.CreateTcpRouteRequest, - dict, -]) -def test_create_tcp_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["tcp_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'address': 'address_value', 'port': 'port_value'}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'original_destination': True}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}} - # 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_tcp_route.CreateTcpRouteRequest.meta.fields["tcp_route"] - - 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["tcp_route"].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["tcp_route"][field])): - del request_init["tcp_route"][field][i][subfield] - else: - del request_init["tcp_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_tcp_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - - request = {} - client.create_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=gcn_tcp_route.CreateTcpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["tcp_route_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 "tcpRouteId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tcp_route._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "tcpRouteId" in jsonified_request - assert jsonified_request["tcpRouteId"] == request_init["tcp_route_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["tcpRouteId"] = 'tcp_route_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tcp_route._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("tcp_route_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 "tcpRouteId" in jsonified_request - assert jsonified_request["tcpRouteId"] == 'tcp_route_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_tcp_route(request) - - expected_params = [ - ( - "tcpRouteId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_tcp_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_tcp_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("tcpRouteId", )) & set(("parent", "tcpRouteId", "tcpRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tcp_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tcp_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_tcp_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_tcp_route.CreateTcpRouteRequest.pb(gcn_tcp_route.CreateTcpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_tcp_route.CreateTcpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tcp_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tcp_route.CreateTcpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_tcp_route(request) - - -def test_create_tcp_route_rest_flattened(): - client = NetworkServicesClient( - 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', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_tcp_route(**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/*}/tcpRoutes" % client.transport._host, args[1]) - - -def test_create_tcp_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tcp_route( - gcn_tcp_route.CreateTcpRouteRequest(), - parent='parent_value', - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - tcp_route_id='tcp_route_id_value', - ) - - -def test_create_tcp_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tcp_route.UpdateTcpRouteRequest, - dict, -]) -def test_update_tcp_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} - request_init["tcp_route"] = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'address': 'address_value', 'port': 'port_value'}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}], 'original_destination': True}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2'], 'labels': {}} - # 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_tcp_route.UpdateTcpRouteRequest.meta.fields["tcp_route"] - - 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["tcp_route"].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["tcp_route"][field])): - del request_init["tcp_route"][field][i][subfield] - else: - del request_init["tcp_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_tcp_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - - request = {} - client.update_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=gcn_tcp_route.UpdateTcpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( - 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 - - response = client.update_tcp_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_tcp_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_tcp_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("tcpRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tcp_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tcp_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_tcp_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_tcp_route.UpdateTcpRouteRequest.pb(gcn_tcp_route.UpdateTcpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_tcp_route.UpdateTcpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tcp_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tcp_route.UpdateTcpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_tcp_route(request) - - -def test_update_tcp_route_rest_flattened(): - client = NetworkServicesClient( - 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 = {'tcp_route': {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - tcp_route=gcn_tcp_route.TcpRoute(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 - - client.update_tcp_route(**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/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}" % client.transport._host, args[1]) - - -def test_update_tcp_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tcp_route( - gcn_tcp_route.UpdateTcpRouteRequest(), - tcp_route=gcn_tcp_route.TcpRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_tcp_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tcp_route.DeleteTcpRouteRequest, - dict, -]) -def test_delete_tcp_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_tcp_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_tcp_route_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 = NetworkServicesClient( - 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_tcp_route 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_tcp_route] = mock_rpc - - request = {} - client.delete_tcp_route(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_tcp_route(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_tcp_route_rest_required_fields(request_type=tcp_route.DeleteTcpRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_tcp_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_tcp_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_tcp_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tcp_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tcp_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_tcp_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tcp_route.DeleteTcpRouteRequest.pb(tcp_route.DeleteTcpRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tcp_route.DeleteTcpRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tcp_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tcp_route_rest_bad_request(transport: str = 'rest', request_type=tcp_route.DeleteTcpRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tcpRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_tcp_route(request) - - -def test_delete_tcp_route_rest_flattened(): - client = NetworkServicesClient( - 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/tcpRoutes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, args[1]) - - -def test_delete_tcp_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tcp_route( - tcp_route.DeleteTcpRouteRequest(), - name='name_value', - ) - - -def test_delete_tcp_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tls_route.ListTlsRoutesRequest, - dict, -]) -def test_list_tls_routes_rest(request_type): - client = NetworkServicesClient( - 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 = tls_route.ListTlsRoutesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tls_route.ListTlsRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tls_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTlsRoutesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_tls_routes_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 = NetworkServicesClient( - 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_tls_routes 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_tls_routes] = mock_rpc - - request = {} - client.list_tls_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tls_routes(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_tls_routes_rest_required_fields(request_type=tls_route.ListTlsRoutesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tls_routes._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_tls_routes._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tls_route.ListTlsRoutesResponse() - # 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 = tls_route.ListTlsRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tls_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tls_routes_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tls_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tls_routes_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tls_routes") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_tls_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tls_route.ListTlsRoutesRequest.pb(tls_route.ListTlsRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tls_route.ListTlsRoutesResponse.to_json(tls_route.ListTlsRoutesResponse()) - - request = tls_route.ListTlsRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tls_route.ListTlsRoutesResponse() - - client.list_tls_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tls_routes_rest_bad_request(transport: str = 'rest', request_type=tls_route.ListTlsRoutesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tls_routes(request) - - -def test_list_tls_routes_rest_flattened(): - client = NetworkServicesClient( - 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 = tls_route.ListTlsRoutesResponse() - - # 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 = tls_route.ListTlsRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tls_routes(**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/*}/tlsRoutes" % client.transport._host, args[1]) - - -def test_list_tls_routes_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tls_routes( - tls_route.ListTlsRoutesRequest(), - parent='parent_value', - ) - - -def test_list_tls_routes_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - next_page_token='abc', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[], - next_page_token='def', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - ], - next_page_token='ghi', - ), - tls_route.ListTlsRoutesResponse( - tls_routes=[ - tls_route.TlsRoute(), - tls_route.TlsRoute(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(tls_route.ListTlsRoutesResponse.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_tls_routes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tls_route.TlsRoute) - for i in results) - - pages = list(client.list_tls_routes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - tls_route.GetTlsRouteRequest, - dict, -]) -def test_get_tls_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute( - name='name_value', - self_link='self_link_value', - description='description_value', - meshes=['meshes_value'], - gateways=['gateways_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tls_route.TlsRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_tls_route(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tls_route.TlsRoute) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.meshes == ['meshes_value'] - assert response.gateways == ['gateways_value'] - -def test_get_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - - request = {} - client.get_tls_route(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_tls_route(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_tls_route_rest_required_fields(request_type=tls_route.GetTlsRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tls_route._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_tls_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tls_route.TlsRoute() - # 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 = tls_route.TlsRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_tls_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_tls_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_tls_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tls_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tls_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_tls_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tls_route.GetTlsRouteRequest.pb(tls_route.GetTlsRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tls_route.TlsRoute.to_json(tls_route.TlsRoute()) - - request = tls_route.GetTlsRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tls_route.TlsRoute() - - client.get_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tls_route_rest_bad_request(transport: str = 'rest', request_type=tls_route.GetTlsRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_tls_route(request) - - -def test_get_tls_route_rest_flattened(): - client = NetworkServicesClient( - 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 = tls_route.TlsRoute() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, args[1]) - - -def test_get_tls_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tls_route( - tls_route.GetTlsRouteRequest(), - name='name_value', - ) - - -def test_get_tls_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tls_route.CreateTlsRouteRequest, - dict, -]) -def test_create_tls_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["tls_route"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'sni_host': ['sni_host_value1', 'sni_host_value2'], 'alpn': ['alpn_value1', 'alpn_value2']}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}]}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2']} - # 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_tls_route.CreateTlsRouteRequest.meta.fields["tls_route"] - - 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["tls_route"].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["tls_route"][field])): - del request_init["tls_route"][field][i][subfield] - else: - del request_init["tls_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_tls_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - - request = {} - client.create_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=gcn_tls_route.CreateTlsRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["tls_route_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 "tlsRouteId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tls_route._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "tlsRouteId" in jsonified_request - assert jsonified_request["tlsRouteId"] == request_init["tls_route_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["tlsRouteId"] = 'tls_route_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tls_route._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("tls_route_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 "tlsRouteId" in jsonified_request - assert jsonified_request["tlsRouteId"] == 'tls_route_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_tls_route(request) - - expected_params = [ - ( - "tlsRouteId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_tls_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_tls_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("tlsRouteId", )) & set(("parent", "tlsRouteId", "tlsRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tls_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tls_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_tls_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_tls_route.CreateTlsRouteRequest.pb(gcn_tls_route.CreateTlsRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_tls_route.CreateTlsRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tls_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tls_route.CreateTlsRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_tls_route(request) - - -def test_create_tls_route_rest_flattened(): - client = NetworkServicesClient( - 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', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_tls_route(**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/*}/tlsRoutes" % client.transport._host, args[1]) - - -def test_create_tls_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tls_route( - gcn_tls_route.CreateTlsRouteRequest(), - parent='parent_value', - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - tls_route_id='tls_route_id_value', - ) - - -def test_create_tls_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_tls_route.UpdateTlsRouteRequest, - dict, -]) -def test_update_tls_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} - request_init["tls_route"] = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'description': 'description_value', 'rules': [{'matches': [{'sni_host': ['sni_host_value1', 'sni_host_value2'], 'alpn': ['alpn_value1', 'alpn_value2']}], 'action': {'destinations': [{'service_name': 'service_name_value', 'weight': 648}]}}], 'meshes': ['meshes_value1', 'meshes_value2'], 'gateways': ['gateways_value1', 'gateways_value2']} - # 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_tls_route.UpdateTlsRouteRequest.meta.fields["tls_route"] - - 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["tls_route"].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["tls_route"][field])): - del request_init["tls_route"][field][i][subfield] - else: - del request_init["tls_route"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_tls_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - - request = {} - client.update_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=gcn_tls_route.UpdateTlsRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tls_route._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_tls_route._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 = NetworkServicesClient( - 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 - - response = client.update_tls_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_tls_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_tls_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("tlsRoute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tls_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tls_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_tls_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_tls_route.UpdateTlsRouteRequest.pb(gcn_tls_route.UpdateTlsRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_tls_route.UpdateTlsRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tls_route_rest_bad_request(transport: str = 'rest', request_type=gcn_tls_route.UpdateTlsRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_tls_route(request) - - -def test_update_tls_route_rest_flattened(): - client = NetworkServicesClient( - 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 = {'tls_route': {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - tls_route=gcn_tls_route.TlsRoute(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 - - client.update_tls_route(**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/{tls_route.name=projects/*/locations/*/tlsRoutes/*}" % client.transport._host, args[1]) - - -def test_update_tls_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tls_route( - gcn_tls_route.UpdateTlsRouteRequest(), - tls_route=gcn_tls_route.TlsRoute(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_tls_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tls_route.DeleteTlsRouteRequest, - dict, -]) -def test_delete_tls_route_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_tls_route(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_tls_route_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 = NetworkServicesClient( - 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_tls_route 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_tls_route] = mock_rpc - - request = {} - client.delete_tls_route(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_tls_route(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_tls_route_rest_required_fields(request_type=tls_route.DeleteTlsRouteRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_tls_route._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_tls_route._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_tls_route(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_tls_route_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_tls_route._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tls_route_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tls_route") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_tls_route") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tls_route.DeleteTlsRouteRequest.pb(tls_route.DeleteTlsRouteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tls_route.DeleteTlsRouteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tls_route(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tls_route_rest_bad_request(transport: str = 'rest', request_type=tls_route.DeleteTlsRouteRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/tlsRoutes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_tls_route(request) - - -def test_delete_tls_route_rest_flattened(): - client = NetworkServicesClient( - 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/tlsRoutes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, args[1]) - - -def test_delete_tls_route_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_tls_route( - tls_route.DeleteTlsRouteRequest(), - name='name_value', - ) - - -def test_delete_tls_route_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - service_binding.ListServiceBindingsRequest, - dict, -]) -def test_list_service_bindings_rest(request_type): - client = NetworkServicesClient( - 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 = service_binding.ListServiceBindingsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service_binding.ListServiceBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_service_bindings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceBindingsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_service_bindings_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 = NetworkServicesClient( - 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_service_bindings 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_service_bindings] = mock_rpc - - request = {} - client.list_service_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_bindings(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_service_bindings_rest_required_fields(request_type=service_binding.ListServiceBindingsRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_service_bindings._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_service_bindings._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service_binding.ListServiceBindingsResponse() - # 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 = service_binding.ListServiceBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_service_bindings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_service_bindings_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_service_bindings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_service_bindings_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_service_bindings") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_service_bindings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_binding.ListServiceBindingsRequest.pb(service_binding.ListServiceBindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_binding.ListServiceBindingsResponse.to_json(service_binding.ListServiceBindingsResponse()) - - request = service_binding.ListServiceBindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_binding.ListServiceBindingsResponse() - - client.list_service_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_service_bindings_rest_bad_request(transport: str = 'rest', request_type=service_binding.ListServiceBindingsRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_service_bindings(request) - - -def test_list_service_bindings_rest_flattened(): - client = NetworkServicesClient( - 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 = service_binding.ListServiceBindingsResponse() - - # 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 = service_binding.ListServiceBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_service_bindings(**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/*}/serviceBindings" % client.transport._host, args[1]) - - -def test_list_service_bindings_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_service_bindings( - service_binding.ListServiceBindingsRequest(), - parent='parent_value', - ) - - -def test_list_service_bindings_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - next_page_token='abc', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[], - next_page_token='def', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - ], - next_page_token='ghi', - ), - service_binding.ListServiceBindingsResponse( - service_bindings=[ - service_binding.ServiceBinding(), - service_binding.ServiceBinding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service_binding.ListServiceBindingsResponse.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_service_bindings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service_binding.ServiceBinding) - for i in results) - - pages = list(client.list_service_bindings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - service_binding.GetServiceBindingRequest, - dict, -]) -def test_get_service_binding_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding( - name='name_value', - description='description_value', - service='service_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service_binding.ServiceBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_service_binding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_binding.ServiceBinding) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.service == 'service_value' - -def test_get_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - - request = {} - client.get_service_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_binding(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_service_binding_rest_required_fields(request_type=service_binding.GetServiceBindingRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_service_binding._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_service_binding._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service_binding.ServiceBinding() - # 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 = service_binding.ServiceBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_service_binding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_service_binding_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_service_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_service_binding_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_service_binding") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_service_binding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_binding.GetServiceBindingRequest.pb(service_binding.GetServiceBindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_binding.ServiceBinding.to_json(service_binding.ServiceBinding()) - - request = service_binding.GetServiceBindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_binding.ServiceBinding() - - client.get_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_service_binding_rest_bad_request(transport: str = 'rest', request_type=service_binding.GetServiceBindingRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_service_binding(request) - - -def test_get_service_binding_rest_flattened(): - client = NetworkServicesClient( - 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 = service_binding.ServiceBinding() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_service_binding(**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/*/serviceBindings/*}" % client.transport._host, args[1]) - - -def test_get_service_binding_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_service_binding( - service_binding.GetServiceBindingRequest(), - name='name_value', - ) - - -def test_get_service_binding_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_service_binding.CreateServiceBindingRequest, - dict, -]) -def test_create_service_binding_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["service_binding"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'service': 'service_value', 'labels': {}} - # 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_service_binding.CreateServiceBindingRequest.meta.fields["service_binding"] - - 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["service_binding"].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["service_binding"][field])): - del request_init["service_binding"][field][i][subfield] - else: - del request_init["service_binding"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_service_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - - request = {} - client.create_service_binding(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_service_binding(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_service_binding_rest_required_fields(request_type=gcn_service_binding.CreateServiceBindingRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["service_binding_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 "serviceBindingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_binding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "serviceBindingId" in jsonified_request - assert jsonified_request["serviceBindingId"] == request_init["service_binding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["serviceBindingId"] = 'service_binding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_binding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("service_binding_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 "serviceBindingId" in jsonified_request - assert jsonified_request["serviceBindingId"] == 'service_binding_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_service_binding(request) - - expected_params = [ - ( - "serviceBindingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_service_binding_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_service_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("serviceBindingId", )) & set(("parent", "serviceBindingId", "serviceBinding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_service_binding_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_service_binding") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_service_binding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_service_binding.CreateServiceBindingRequest.pb(gcn_service_binding.CreateServiceBindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_service_binding.CreateServiceBindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_service_binding_rest_bad_request(transport: str = 'rest', request_type=gcn_service_binding.CreateServiceBindingRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_service_binding(request) - - -def test_create_service_binding_rest_flattened(): - client = NetworkServicesClient( - 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', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_service_binding(**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/*}/serviceBindings" % client.transport._host, args[1]) - - -def test_create_service_binding_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_service_binding( - gcn_service_binding.CreateServiceBindingRequest(), - parent='parent_value', - service_binding=gcn_service_binding.ServiceBinding(name='name_value'), - service_binding_id='service_binding_id_value', - ) - - -def test_create_service_binding_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - service_binding.DeleteServiceBindingRequest, - dict, -]) -def test_delete_service_binding_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_service_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_service_binding_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 = NetworkServicesClient( - 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_service_binding 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_service_binding] = mock_rpc - - request = {} - client.delete_service_binding(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_service_binding(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_service_binding_rest_required_fields(request_type=service_binding.DeleteServiceBindingRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_service_binding._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_service_binding._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_service_binding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_service_binding_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_service_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_service_binding_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_service_binding") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_service_binding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_binding.DeleteServiceBindingRequest.pb(service_binding.DeleteServiceBindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = service_binding.DeleteServiceBindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_service_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_service_binding_rest_bad_request(transport: str = 'rest', request_type=service_binding.DeleteServiceBindingRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serviceBindings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_service_binding(request) - - -def test_delete_service_binding_rest_flattened(): - client = NetworkServicesClient( - 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/serviceBindings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_service_binding(**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/*/serviceBindings/*}" % client.transport._host, args[1]) - - -def test_delete_service_binding_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_service_binding( - service_binding.DeleteServiceBindingRequest(), - name='name_value', - ) - - -def test_delete_service_binding_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - mesh.ListMeshesRequest, - dict, -]) -def test_list_meshes_rest(request_type): - client = NetworkServicesClient( - 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 = mesh.ListMeshesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mesh.ListMeshesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_meshes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMeshesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_meshes_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 = NetworkServicesClient( - 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_meshes 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_meshes] = mock_rpc - - request = {} - client.list_meshes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_meshes(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_meshes_rest_required_fields(request_type=mesh.ListMeshesRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_meshes._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_meshes._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mesh.ListMeshesResponse() - # 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 = mesh.ListMeshesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_meshes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_meshes_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_meshes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_meshes_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_meshes") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_list_meshes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = mesh.ListMeshesRequest.pb(mesh.ListMeshesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mesh.ListMeshesResponse.to_json(mesh.ListMeshesResponse()) - - request = mesh.ListMeshesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mesh.ListMeshesResponse() - - client.list_meshes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_meshes_rest_bad_request(transport: str = 'rest', request_type=mesh.ListMeshesRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_meshes(request) - - -def test_list_meshes_rest_flattened(): - client = NetworkServicesClient( - 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 = mesh.ListMeshesResponse() - - # 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 = mesh.ListMeshesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_meshes(**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/*}/meshes" % client.transport._host, args[1]) - - -def test_list_meshes_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_meshes( - mesh.ListMeshesRequest(), - parent='parent_value', - ) - - -def test_list_meshes_rest_pager(transport: str = 'rest'): - client = NetworkServicesClient( - 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 = ( - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - mesh.Mesh(), - ], - next_page_token='abc', - ), - mesh.ListMeshesResponse( - meshes=[], - next_page_token='def', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - ], - next_page_token='ghi', - ), - mesh.ListMeshesResponse( - meshes=[ - mesh.Mesh(), - mesh.Mesh(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(mesh.ListMeshesResponse.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_meshes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mesh.Mesh) - for i in results) - - pages = list(client.list_meshes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - mesh.GetMeshRequest, - dict, -]) -def test_get_mesh_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/meshes/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 = mesh.Mesh( - name='name_value', - self_link='self_link_value', - description='description_value', - interception_port=1848, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mesh.Mesh.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_mesh(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, mesh.Mesh) - assert response.name == 'name_value' - assert response.self_link == 'self_link_value' - assert response.description == 'description_value' - assert response.interception_port == 1848 - -def test_get_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - - request = {} - client.get_mesh(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mesh(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_mesh_rest_required_fields(request_type=mesh.GetMeshRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_mesh._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_mesh._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mesh.Mesh() - # 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 = mesh.Mesh.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_mesh(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_mesh_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_mesh._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_mesh_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_mesh") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_get_mesh") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = mesh.GetMeshRequest.pb(mesh.GetMeshRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mesh.Mesh.to_json(mesh.Mesh()) - - request = mesh.GetMeshRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mesh.Mesh() - - client.get_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_mesh_rest_bad_request(transport: str = 'rest', request_type=mesh.GetMeshRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_mesh(request) - - -def test_get_mesh_rest_flattened(): - client = NetworkServicesClient( - 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 = mesh.Mesh() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/meshes/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 = mesh.Mesh.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_mesh(**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/*/meshes/*}" % client.transport._host, args[1]) - - -def test_get_mesh_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_mesh( - mesh.GetMeshRequest(), - name='name_value', - ) - - -def test_get_mesh_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_mesh.CreateMeshRequest, - dict, -]) -def test_create_mesh_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["mesh"] = {'name': 'name_value', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'interception_port': 1848} - # 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_mesh.CreateMeshRequest.meta.fields["mesh"] - - 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["mesh"].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["mesh"][field])): - del request_init["mesh"][field][i][subfield] - else: - del request_init["mesh"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_mesh(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - - request = {} - client.create_mesh(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_mesh(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_mesh_rest_required_fields(request_type=gcn_mesh.CreateMeshRequest): - transport_class = transports.NetworkServicesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["mesh_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 "meshId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mesh._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "meshId" in jsonified_request - assert jsonified_request["meshId"] == request_init["mesh_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["meshId"] = 'mesh_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mesh._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("mesh_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 "meshId" in jsonified_request - assert jsonified_request["meshId"] == 'mesh_id_value' - - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_mesh(request) - - expected_params = [ - ( - "meshId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_mesh_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_mesh._get_unset_required_fields({}) - assert set(unset_fields) == (set(("meshId", )) & set(("parent", "meshId", "mesh", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_mesh_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_mesh") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_create_mesh") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_mesh.CreateMeshRequest.pb(gcn_mesh.CreateMeshRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_mesh.CreateMeshRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_mesh_rest_bad_request(transport: str = 'rest', request_type=gcn_mesh.CreateMeshRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_mesh(request) - - -def test_create_mesh_rest_flattened(): - client = NetworkServicesClient( - 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', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_mesh(**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/*}/meshes" % client.transport._host, args[1]) - - -def test_create_mesh_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_mesh( - gcn_mesh.CreateMeshRequest(), - parent='parent_value', - mesh=gcn_mesh.Mesh(name='name_value'), - mesh_id='mesh_id_value', - ) - - -def test_create_mesh_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_mesh.UpdateMeshRequest, - dict, -]) -def test_update_mesh_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} - request_init["mesh"] = {'name': 'projects/sample1/locations/sample2/meshes/sample3', 'self_link': 'self_link_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'description': 'description_value', 'interception_port': 1848} - # 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_mesh.UpdateMeshRequest.meta.fields["mesh"] - - 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["mesh"].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["mesh"][field])): - del request_init["mesh"][field][i][subfield] - else: - del request_init["mesh"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_mesh(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - - request = {} - client.update_mesh(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_mesh(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_mesh_rest_required_fields(request_type=gcn_mesh.UpdateMeshRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_mesh._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_mesh._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 = NetworkServicesClient( - 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 - - response = client.update_mesh(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_mesh_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_mesh._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("mesh", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_mesh_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_mesh") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_update_mesh") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcn_mesh.UpdateMeshRequest.pb(gcn_mesh.UpdateMeshRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcn_mesh.UpdateMeshRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_mesh_rest_bad_request(transport: str = 'rest', request_type=gcn_mesh.UpdateMeshRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_mesh(request) - - -def test_update_mesh_rest_flattened(): - client = NetworkServicesClient( - 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 = {'mesh': {'name': 'projects/sample1/locations/sample2/meshes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - mesh=gcn_mesh.Mesh(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 - - client.update_mesh(**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/{mesh.name=projects/*/locations/*/meshes/*}" % client.transport._host, args[1]) - - -def test_update_mesh_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_mesh( - gcn_mesh.UpdateMeshRequest(), - mesh=gcn_mesh.Mesh(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_mesh_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - mesh.DeleteMeshRequest, - dict, -]) -def test_delete_mesh_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_mesh(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_mesh_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 = NetworkServicesClient( - 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_mesh 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_mesh] = mock_rpc - - request = {} - client.delete_mesh(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_mesh(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_mesh_rest_required_fields(request_type=mesh.DeleteMeshRequest): - transport_class = transports.NetworkServicesRestTransport - - 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_mesh._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_mesh._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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_mesh(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_mesh_rest_unset_required_fields(): - transport = transports.NetworkServicesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_mesh._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_mesh_rest_interceptors(null_interceptor): - transport = transports.NetworkServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkServicesRestInterceptor(), - ) - client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_mesh") as post, \ - mock.patch.object(transports.NetworkServicesRestInterceptor, "pre_delete_mesh") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = mesh.DeleteMeshRequest.pb(mesh.DeleteMeshRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = mesh.DeleteMeshRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_mesh(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_mesh_rest_bad_request(transport: str = 'rest', request_type=mesh.DeleteMeshRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/meshes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_mesh(request) - - -def test_delete_mesh_rest_flattened(): - client = NetworkServicesClient( - 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/meshes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_mesh(**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/*/meshes/*}" % client.transport._host, args[1]) - - -def test_delete_mesh_rest_flattened_error(transport: str = 'rest'): - client = NetworkServicesClient( - 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_mesh( - mesh.DeleteMeshRequest(), - name='name_value', - ) - - -def test_delete_mesh_rest_error(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkServicesClient( - 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 = NetworkServicesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NetworkServicesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.NetworkServicesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.NetworkServicesGrpcTransport, - transports.NetworkServicesGrpcAsyncIOTransport, - transports.NetworkServicesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = NetworkServicesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NetworkServicesGrpcTransport, - ) - -def test_network_services_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NetworkServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_network_services_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_services_v1.services.network_services.transports.NetworkServicesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.NetworkServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_endpoint_policies', - 'get_endpoint_policy', - 'create_endpoint_policy', - 'update_endpoint_policy', - 'delete_endpoint_policy', - 'list_gateways', - 'get_gateway', - 'create_gateway', - 'update_gateway', - 'delete_gateway', - 'list_grpc_routes', - 'get_grpc_route', - 'create_grpc_route', - 'update_grpc_route', - 'delete_grpc_route', - 'list_http_routes', - 'get_http_route', - 'create_http_route', - 'update_http_route', - 'delete_http_route', - 'list_tcp_routes', - 'get_tcp_route', - 'create_tcp_route', - 'update_tcp_route', - 'delete_tcp_route', - 'list_tls_routes', - 'get_tls_route', - 'create_tls_route', - 'update_tls_route', - 'delete_tls_route', - 'list_service_bindings', - 'get_service_binding', - 'create_service_binding', - 'delete_service_binding', - 'list_meshes', - 'get_mesh', - 'create_mesh', - 'update_mesh', - 'delete_mesh', - '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_services_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_services_v1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkServicesTransport( - 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_services_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_services_v1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkServicesTransport() - adc.assert_called_once() - - -def test_network_services_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) - NetworkServicesClient() - 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.NetworkServicesGrpcTransport, - transports.NetworkServicesGrpcAsyncIOTransport, - ], -) -def test_network_services_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.NetworkServicesGrpcTransport, - transports.NetworkServicesGrpcAsyncIOTransport, - transports.NetworkServicesRestTransport, - ], -) -def test_network_services_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.NetworkServicesGrpcTransport, grpc_helpers), - (transports.NetworkServicesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_network_services_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( - "networkservices.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="networkservices.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) -def test_network_services_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_services_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.NetworkServicesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_network_services_rest_lro_client(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_services_host_no_port(transport_name): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkservices.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkservices.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_services_host_with_port(transport_name): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networkservices.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networkservices.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networkservices.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_network_services_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = NetworkServicesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = NetworkServicesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_endpoint_policies._session - session2 = client2.transport.list_endpoint_policies._session - assert session1 != session2 - session1 = client1.transport.get_endpoint_policy._session - session2 = client2.transport.get_endpoint_policy._session - assert session1 != session2 - session1 = client1.transport.create_endpoint_policy._session - session2 = client2.transport.create_endpoint_policy._session - assert session1 != session2 - session1 = client1.transport.update_endpoint_policy._session - session2 = client2.transport.update_endpoint_policy._session - assert session1 != session2 - session1 = client1.transport.delete_endpoint_policy._session - session2 = client2.transport.delete_endpoint_policy._session - assert session1 != session2 - session1 = client1.transport.list_gateways._session - session2 = client2.transport.list_gateways._session - assert session1 != session2 - session1 = client1.transport.get_gateway._session - session2 = client2.transport.get_gateway._session - assert session1 != session2 - session1 = client1.transport.create_gateway._session - session2 = client2.transport.create_gateway._session - assert session1 != session2 - session1 = client1.transport.update_gateway._session - session2 = client2.transport.update_gateway._session - assert session1 != session2 - session1 = client1.transport.delete_gateway._session - session2 = client2.transport.delete_gateway._session - assert session1 != session2 - session1 = client1.transport.list_grpc_routes._session - session2 = client2.transport.list_grpc_routes._session - assert session1 != session2 - session1 = client1.transport.get_grpc_route._session - session2 = client2.transport.get_grpc_route._session - assert session1 != session2 - session1 = client1.transport.create_grpc_route._session - session2 = client2.transport.create_grpc_route._session - assert session1 != session2 - session1 = client1.transport.update_grpc_route._session - session2 = client2.transport.update_grpc_route._session - assert session1 != session2 - session1 = client1.transport.delete_grpc_route._session - session2 = client2.transport.delete_grpc_route._session - assert session1 != session2 - session1 = client1.transport.list_http_routes._session - session2 = client2.transport.list_http_routes._session - assert session1 != session2 - session1 = client1.transport.get_http_route._session - session2 = client2.transport.get_http_route._session - assert session1 != session2 - session1 = client1.transport.create_http_route._session - session2 = client2.transport.create_http_route._session - assert session1 != session2 - session1 = client1.transport.update_http_route._session - session2 = client2.transport.update_http_route._session - assert session1 != session2 - session1 = client1.transport.delete_http_route._session - session2 = client2.transport.delete_http_route._session - assert session1 != session2 - session1 = client1.transport.list_tcp_routes._session - session2 = client2.transport.list_tcp_routes._session - assert session1 != session2 - session1 = client1.transport.get_tcp_route._session - session2 = client2.transport.get_tcp_route._session - assert session1 != session2 - session1 = client1.transport.create_tcp_route._session - session2 = client2.transport.create_tcp_route._session - assert session1 != session2 - session1 = client1.transport.update_tcp_route._session - session2 = client2.transport.update_tcp_route._session - assert session1 != session2 - session1 = client1.transport.delete_tcp_route._session - session2 = client2.transport.delete_tcp_route._session - assert session1 != session2 - session1 = client1.transport.list_tls_routes._session - session2 = client2.transport.list_tls_routes._session - assert session1 != session2 - session1 = client1.transport.get_tls_route._session - session2 = client2.transport.get_tls_route._session - assert session1 != session2 - session1 = client1.transport.create_tls_route._session - session2 = client2.transport.create_tls_route._session - assert session1 != session2 - session1 = client1.transport.update_tls_route._session - session2 = client2.transport.update_tls_route._session - assert session1 != session2 - session1 = client1.transport.delete_tls_route._session - session2 = client2.transport.delete_tls_route._session - assert session1 != session2 - session1 = client1.transport.list_service_bindings._session - session2 = client2.transport.list_service_bindings._session - assert session1 != session2 - session1 = client1.transport.get_service_binding._session - session2 = client2.transport.get_service_binding._session - assert session1 != session2 - session1 = client1.transport.create_service_binding._session - session2 = client2.transport.create_service_binding._session - assert session1 != session2 - session1 = client1.transport.delete_service_binding._session - session2 = client2.transport.delete_service_binding._session - assert session1 != session2 - session1 = client1.transport.list_meshes._session - session2 = client2.transport.list_meshes._session - assert session1 != session2 - session1 = client1.transport.get_mesh._session - session2 = client2.transport.get_mesh._session - assert session1 != session2 - session1 = client1.transport.create_mesh._session - session2 = client2.transport.create_mesh._session - assert session1 != session2 - session1 = client1.transport.update_mesh._session - session2 = client2.transport.update_mesh._session - assert session1 != session2 - session1 = client1.transport.delete_mesh._session - session2 = client2.transport.delete_mesh._session - assert session1 != session2 -def test_network_services_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkServicesGrpcTransport( - 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_services_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkServicesGrpcAsyncIOTransport( - 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.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) -def test_network_services_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.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport]) -def test_network_services_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_services_grpc_lro_client(): - client = NetworkServicesClient( - 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_services_grpc_lro_async_client(): - client = NetworkServicesAsyncClient( - 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 = NetworkServicesClient.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 = NetworkServicesClient.authorization_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_authorization_policy_path(path) - assert expected == actual - -def test_backend_service_path(): - project = "cuttlefish" - location = "mussel" - backend_service = "winkle" - expected = "projects/{project}/locations/{location}/backendServices/{backend_service}".format(project=project, location=location, backend_service=backend_service, ) - actual = NetworkServicesClient.backend_service_path(project, location, backend_service) - assert expected == actual - - -def test_parse_backend_service_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "backend_service": "abalone", - } - path = NetworkServicesClient.backend_service_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_backend_service_path(path) - assert expected == actual - -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 = NetworkServicesClient.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 = NetworkServicesClient.client_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_client_tls_policy_path(path) - assert expected == actual - -def test_endpoint_policy_path(): - project = "cuttlefish" - location = "mussel" - endpoint_policy = "winkle" - expected = "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format(project=project, location=location, endpoint_policy=endpoint_policy, ) - actual = NetworkServicesClient.endpoint_policy_path(project, location, endpoint_policy) - assert expected == actual - - -def test_parse_endpoint_policy_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "endpoint_policy": "abalone", - } - path = NetworkServicesClient.endpoint_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_endpoint_policy_path(path) - assert expected == actual - -def test_gateway_path(): - project = "squid" - location = "clam" - gateway = "whelk" - expected = "projects/{project}/locations/{location}/gateways/{gateway}".format(project=project, location=location, gateway=gateway, ) - actual = NetworkServicesClient.gateway_path(project, location, gateway) - assert expected == actual - - -def test_parse_gateway_path(): - expected = { - "project": "octopus", - "location": "oyster", - "gateway": "nudibranch", - } - path = NetworkServicesClient.gateway_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_gateway_path(path) - assert expected == actual - -def test_grpc_route_path(): - project = "cuttlefish" - location = "mussel" - grpc_route = "winkle" - expected = "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format(project=project, location=location, grpc_route=grpc_route, ) - actual = NetworkServicesClient.grpc_route_path(project, location, grpc_route) - assert expected == actual - - -def test_parse_grpc_route_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "grpc_route": "abalone", - } - path = NetworkServicesClient.grpc_route_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_grpc_route_path(path) - assert expected == actual - -def test_http_route_path(): - project = "squid" - location = "clam" - http_route = "whelk" - expected = "projects/{project}/locations/{location}/httpRoutes/{http_route}".format(project=project, location=location, http_route=http_route, ) - actual = NetworkServicesClient.http_route_path(project, location, http_route) - assert expected == actual - - -def test_parse_http_route_path(): - expected = { - "project": "octopus", - "location": "oyster", - "http_route": "nudibranch", - } - path = NetworkServicesClient.http_route_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_http_route_path(path) - assert expected == actual - -def test_mesh_path(): - project = "cuttlefish" - location = "mussel" - mesh = "winkle" - expected = "projects/{project}/locations/{location}/meshes/{mesh}".format(project=project, location=location, mesh=mesh, ) - actual = NetworkServicesClient.mesh_path(project, location, mesh) - assert expected == actual - - -def test_parse_mesh_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "mesh": "abalone", - } - path = NetworkServicesClient.mesh_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_mesh_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 = NetworkServicesClient.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 = NetworkServicesClient.server_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_server_tls_policy_path(path) - assert expected == actual - -def test_service_binding_path(): - project = "cuttlefish" - location = "mussel" - service_binding = "winkle" - expected = "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format(project=project, location=location, service_binding=service_binding, ) - actual = NetworkServicesClient.service_binding_path(project, location, service_binding) - assert expected == actual - - -def test_parse_service_binding_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "service_binding": "abalone", - } - path = NetworkServicesClient.service_binding_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_service_binding_path(path) - assert expected == actual - -def test_tcp_route_path(): - project = "squid" - location = "clam" - tcp_route = "whelk" - expected = "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format(project=project, location=location, tcp_route=tcp_route, ) - actual = NetworkServicesClient.tcp_route_path(project, location, tcp_route) - assert expected == actual - - -def test_parse_tcp_route_path(): - expected = { - "project": "octopus", - "location": "oyster", - "tcp_route": "nudibranch", - } - path = NetworkServicesClient.tcp_route_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_tcp_route_path(path) - assert expected == actual - -def test_tls_route_path(): - project = "cuttlefish" - location = "mussel" - tls_route = "winkle" - expected = "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format(project=project, location=location, tls_route=tls_route, ) - actual = NetworkServicesClient.tls_route_path(project, location, tls_route) - assert expected == actual - - -def test_parse_tls_route_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "tls_route": "abalone", - } - path = NetworkServicesClient.tls_route_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_tls_route_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = NetworkServicesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = NetworkServicesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = NetworkServicesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = NetworkServicesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = NetworkServicesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = NetworkServicesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = NetworkServicesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = NetworkServicesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = NetworkServicesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = NetworkServicesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkServicesClient.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.NetworkServicesTransport, '_prep_wrapped_messages') as prep: - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.NetworkServicesTransport, '_prep_wrapped_messages') as prep: - transport_class = NetworkServicesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/edgeCacheKeysets/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = NetworkServicesClient( - 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 = NetworkServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = NetworkServicesClient( - 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", [ - (NetworkServicesClient, transports.NetworkServicesGrpcTransport), - (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport), -]) -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/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/async_client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/async_client.py index 76a6091f6160..ea08b350be26 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/async_client.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/async_client.py @@ -51,6 +51,7 @@ 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 struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.network_services_v1.services.dep_service import pagers @@ -714,7 +715,7 @@ async def sample_update_lb_traffic_extension(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Used to specify the fields to be overwritten + Optional. Used to specify the fields to be overwritten in the ``LbTrafficExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is @@ -1366,7 +1367,7 @@ async def sample_update_lb_route_extension(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Used to specify the fields to be overwritten + Optional. Used to specify the fields to be overwritten in the ``LbRouteExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is overwritten diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/client.py index 921a1a64906e..36f6d8fea289 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/client.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/client.py @@ -56,6 +56,7 @@ 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 struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.network_services_v1.services.dep_service import pagers @@ -1146,7 +1147,7 @@ def sample_update_lb_traffic_extension(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Used to specify the fields to be overwritten + Optional. Used to specify the fields to be overwritten in the ``LbTrafficExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is @@ -1789,7 +1790,7 @@ def sample_update_lb_route_extension(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Used to specify the fields to be overwritten + Optional. Used to specify the fields to be overwritten in the ``LbRouteExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is overwritten diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/transports/rest.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/transports/rest.py index 6a688877fcd5..6cba38871715 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/transports/rest.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/dep_service/transports/rest.py @@ -1478,9 +1478,7 @@ class _UpdateLbRouteExtension(DepServiceRestStub): def __hash__(self): return hash("UpdateLbRouteExtension") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -1575,9 +1573,7 @@ class _UpdateLbTrafficExtension(DepServiceRestStub): def __hash__(self): return hash("UpdateLbTrafficExtension") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/types/dep.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/types/dep.py index c26f82828c9a..4a53c636c866 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/types/dep.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/types/dep.py @@ -19,6 +19,7 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -179,8 +180,8 @@ class Extension(proto.Message): supported_events (MutableSequence[google.cloud.network_services_v1.types.EventType]): Optional. A set of events during request or response processing for which this extension is called. This field is - required for the ``LbTrafficExtension`` resource. It's not - relevant for the ``LbRouteExtension`` resource. + required for the ``LbTrafficExtension`` resource. It must + not be set for the ``LbRouteExtension`` resource. timeout (google.protobuf.duration_pb2.Duration): Optional. Specifies the timeout for each individual message on the stream. The timeout @@ -305,6 +306,15 @@ class LbTrafficExtension(proto.Message): ``EXTERNAL_MANAGED``. For more information, refer to `Choosing a load balancer `__. + metadata (google.protobuf.struct_pb2.Struct): + Optional. The metadata provided here is included in the + ``ProcessingRequest.metadata_context.filter_metadata`` map + field. The metadata is available under the key + ``com.google.lb_traffic_extension.``. The + following variables are supported in the metadata: + + ``{forwarding_rule_id}`` - substituted with the forwarding + rule's fully qualified resource name. """ name: str = proto.Field( @@ -344,6 +354,11 @@ class LbTrafficExtension(proto.Message): number=8, enum="LoadBalancingScheme", ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) class ListLbTrafficExtensionsRequest(proto.Message): @@ -498,7 +513,7 @@ class UpdateLbTrafficExtensionRequest(proto.Message): Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Used to specify the fields to be overwritten in + Optional. Used to specify the fields to be overwritten in the ``LbTrafficExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is overwritten if it @@ -630,6 +645,17 @@ class LbRouteExtension(proto.Message): ``EXTERNAL_MANAGED``. For more information, refer to `Choosing a load balancer `__. + metadata (google.protobuf.struct_pb2.Struct): + Optional. The metadata provided here is included as part of + the ``metadata_context`` (of type + ``google.protobuf.Struct``) in the ``ProcessingRequest`` + message sent to the extension server. The metadata is + available under the namespace + ``com.google.lb_route_extension.``. The + following variables are supported in the metadata Struct: + + ``{forwarding_rule_id}`` - substituted with the forwarding + rule's fully qualified resource name. """ name: str = proto.Field( @@ -669,6 +695,11 @@ class LbRouteExtension(proto.Message): number=8, enum="LoadBalancingScheme", ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) class ListLbRouteExtensionsRequest(proto.Message): @@ -823,7 +854,7 @@ class UpdateLbRouteExtensionRequest(proto.Message): Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Used to specify the fields to be overwritten in + Optional. Used to specify the fields to be overwritten in the ``LbRouteExtension`` resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field is overwritten if it is in the diff --git a/packages/google-cloud-network-services/scripts/fixup_network_services_v1_keywords.py b/packages/google-cloud-network-services/scripts/fixup_network_services_v1_keywords.py index 380d90eaecf1..22a35f3c0c14 100644 --- a/packages/google-cloud-network-services/scripts/fixup_network_services_v1_keywords.py +++ b/packages/google-cloud-network-services/scripts/fixup_network_services_v1_keywords.py @@ -83,8 +83,8 @@ class network_servicesCallTransformer(cst.CSTTransformer): 'update_gateway': ('gateway', 'update_mask', ), 'update_grpc_route': ('grpc_route', 'update_mask', ), 'update_http_route': ('http_route', 'update_mask', ), - 'update_lb_route_extension': ('update_mask', 'lb_route_extension', 'request_id', ), - 'update_lb_traffic_extension': ('update_mask', 'lb_traffic_extension', 'request_id', ), + 'update_lb_route_extension': ('lb_route_extension', 'update_mask', 'request_id', ), + 'update_lb_traffic_extension': ('lb_traffic_extension', 'update_mask', 'request_id', ), 'update_mesh': ('mesh', 'update_mask', ), 'update_tcp_route': ('tcp_route', 'update_mask', ), 'update_tls_route': ('tls_route', 'update_mask', ), diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_dep_service.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_dep_service.py index d29f8740aa39..8520369230fd 100644 --- a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_dep_service.py +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_dep_service.py @@ -51,6 +51,7 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import json_format +from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio @@ -6266,6 +6267,7 @@ def test_create_lb_traffic_extension_rest(request_type): } ], "load_balancing_scheme": 1, + "metadata": {"fields": {}}, } # 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 @@ -6714,6 +6716,7 @@ def test_update_lb_traffic_extension_rest(request_type): } ], "load_balancing_scheme": 1, + "metadata": {"fields": {}}, } # 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 @@ -6936,12 +6939,7 @@ def test_update_lb_traffic_extension_rest_unset_required_fields(): "updateMask", ) ) - & set( - ( - "updateMask", - "lbTrafficExtension", - ) - ) + & set(("lbTrafficExtension",)) ) @@ -8154,6 +8152,7 @@ def test_create_lb_route_extension_rest(request_type): } ], "load_balancing_scheme": 1, + "metadata": {"fields": {}}, } # 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 @@ -8599,6 +8598,7 @@ def test_update_lb_route_extension_rest(request_type): } ], "load_balancing_scheme": 1, + "metadata": {"fields": {}}, } # 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 @@ -8819,12 +8819,7 @@ def test_update_lb_route_extension_rest_unset_required_fields(): "updateMask", ) ) - & set( - ( - "updateMask", - "lbRouteExtension", - ) - ) + & set(("lbRouteExtension",)) )