diff --git a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/_mixins.py.j2 b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/_mixins.py.j2 index 6dd04dfb18..eb19c3c8bd 100644 --- a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/_mixins.py.j2 +++ b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/_mixins.py.j2 @@ -3,7 +3,7 @@ {% if "ListOperations" in api.mixin_api_methods %} def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -27,8 +27,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -38,12 +42,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -53,7 +57,7 @@ {% if "GetOperation" in api.mixin_api_methods %} def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -77,8 +81,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -88,12 +96,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -102,7 +110,7 @@ {% if "DeleteOperation" in api.mixin_api_methods %} def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -130,8 +138,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -141,17 +153,17 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "CancelOperation" in api.mixin_api_methods %} def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -178,8 +190,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -189,17 +205,17 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "WaitOperation" in api.mixin_api_methods %} def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -229,8 +245,12 @@ # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -240,7 +260,7 @@ # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -254,7 +274,7 @@ {% if "SetIamPolicy" in api.mixin_api_methods %} def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -344,8 +364,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -355,12 +379,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -369,7 +393,7 @@ {% if "GetIamPolicy" in api.mixin_api_methods %} def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -460,8 +484,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -471,12 +499,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -485,7 +513,7 @@ {% if "TestIamPermissions" in api.mixin_api_methods %} def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -514,8 +542,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -525,12 +557,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -543,7 +575,7 @@ {% if "GetLocation" in api.mixin_api_methods %} def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -567,8 +599,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -578,12 +614,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -592,7 +628,7 @@ {% if "ListLocations" in api.mixin_api_methods %} def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -616,8 +652,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -627,12 +667,12 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/client.py.j2 b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/client.py.j2 index 2b85bd9e76..445d51935c 100644 --- a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/client.py.j2 +++ b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/client.py.j2 @@ -100,7 +100,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): This class implements API version {{ service.version }}.{% endif %}""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -108,7 +108,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -118,6 +118,9 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -540,7 +543,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): {% if opts.add_iam_methods %} def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -630,8 +633,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -645,19 +652,19 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -747,8 +754,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -762,19 +773,19 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -803,8 +814,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -818,12 +833,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/transports/base.py.j2 b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/transports/base.py.j2 index 9cb924a529..a5a5855deb 100644 --- a/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/transports/base.py.j2 +++ b/gapic/ads-templates/%namespace/%name/%version/%sub/services/%service/transports/base.py.j2 @@ -3,7 +3,7 @@ {% block content %} import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union import google.auth # type: ignore import google.api_core # type: ignore @@ -98,6 +98,8 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + # Save the scopes. self._scopes = scopes diff --git a/gapic/ads-templates/noxfile.py.j2 b/gapic/ads-templates/noxfile.py.j2 index 48646feb5e..075dc7eaee 100644 --- a/gapic/ads-templates/noxfile.py.j2 +++ b/gapic/ads-templates/noxfile.py.j2 @@ -52,5 +52,7 @@ def mypy(session): {% else %} '{{ api.naming.versioned_module_name }}', {% endif %} + "--check-untyped-defs", + *session.posargs, ) {% endblock %} diff --git a/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 b/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 index d7f8bb7e68..e19793749d 100644 --- a/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 +++ b/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 @@ -130,6 +130,24 @@ def test_delete_operation_from_dict(): ) call.assert_called() + +def test_delete_operation_flattened(): + client = {{ service.client_name }}( + 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 + + client.delete_operation() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + {% endif %} {# DeleteOperation #} {% if "CancelOperation" in api.mixin_api_methods %} @@ -196,6 +214,24 @@ def test_cancel_operation_from_dict(): } ) call.assert_called() + + +def test_cancel_operation_flattened(): + client = {{ service.client_name }}( + 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 + + client.cancel_operation() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() {% endif %} {# CancelOperation #} {% if "WaitOperation" in api.mixin_api_methods %} @@ -264,6 +300,24 @@ def test_wait_operation_from_dict(): ) call.assert_called() + +def test_wait_operation_flattened(): + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.wait_operation() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() + {% endif %} {# WaitOperation #} {% if "GetOperation" in api.mixin_api_methods %} @@ -333,6 +387,24 @@ def test_get_operation_from_dict(): call.assert_called() + +def test_get_operation_flattened(): + client = {{ service.client_name }}( + 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() + + client.get_operation() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + {% endif %} {# GetOperation #} {% if "ListOperations" in api.mixin_api_methods %} @@ -401,6 +473,24 @@ def test_list_operations_from_dict(): call.assert_called() + +def test_list_operations_flattened(): + client = {{ service.client_name }}( + 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() + + client.list_operations() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + {% endif %} {# ListOperations #} {% endif %} {# LRO #} @@ -471,6 +561,24 @@ def test_list_locations_from_dict(): ) call.assert_called() + +def test_list_locations_flattened(): + client = {{ service.client_name }}( + 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() + + client.list_locations() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + {% endif %} {# ListLocations #} {# GetLocation #} @@ -537,6 +645,24 @@ def test_get_location_from_dict(): ) call.assert_called() + +def test_get_location_flattened(): + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # 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() + + client.get_location() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + {% endif %} {# GetLocation #} {% endif %} {# location_mixin #} @@ -614,6 +740,24 @@ def test_set_iam_policy_from_dict(): call.assert_called() +def test_set_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + def test_get_iam_policy(transport: str = "grpc"): client = {{ service.client_name }}( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -687,6 +831,24 @@ def test_get_iam_policy_from_dict(): call.assert_called() +def test_get_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + def test_test_iam_permissions(transport: str = "grpc"): client = {{ service.client_name }}( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -766,6 +928,24 @@ def test_test_iam_permissions_from_dict(): ) call.assert_called() + +def test_test_iam_permissions_flattened(): + client = {{ service.client_name }}( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + {% endif %} {% if (not opts.add_iam_methods and api.has_iam_mixin) and 'grpc' in opts.transport %} @@ -839,6 +1019,24 @@ def test_set_iam_policy_from_dict(): } ) call.assert_called() + + +def test_set_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() {% endif %} {% if "GetIamPolicy" in api.mixin_api_methods %} @@ -913,6 +1111,24 @@ def test_get_iam_policy_from_dict(): } ) call.assert_called() + + +def test_get_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() {% endif %} {% if "TestIamPermissions" in api.mixin_api_methods %} @@ -994,6 +1210,24 @@ def test_test_iam_permissions_from_dict(): } ) call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = {{ service.client_name }}( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() {% endif %} {% endif %} diff --git a/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index ac385e285d..39d5fa7d35 100644 --- a/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -94,6 +94,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert {{ service.client_name }}._get_default_mtls_endpoint(None) is None assert {{ service.client_name }}._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -101,6 +102,7 @@ def test__get_default_mtls_endpoint(): assert {{ service.client_name }}._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert {{ service.client_name }}._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert {{ service.client_name }}._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert {{ service.client_name }}._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint @pytest.mark.parametrize("client_class,transport_name", [ diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_async_mixins.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_async_mixins.py.j2 index 60b8f0a7e9..9f5ba3369b 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_async_mixins.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_async_mixins.py.j2 @@ -5,7 +5,7 @@ {% if "ListOperations" in api.mixin_api_methods %} async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -28,8 +28,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -39,7 +43,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -47,7 +51,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -57,7 +61,7 @@ {% if "GetOperation" in api.mixin_api_methods %} async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -80,8 +84,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -91,7 +99,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -99,7 +107,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -108,7 +116,7 @@ {% if "DeleteOperation" in api.mixin_api_methods %} async def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -135,8 +143,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -146,20 +158,20 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "CancelOperation" in api.mixin_api_methods %} async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -185,8 +197,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -196,20 +212,20 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "WaitOperation" in api.mixin_api_methods %} async def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -238,8 +254,12 @@ # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -249,7 +269,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -257,7 +277,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -271,7 +291,7 @@ {% if "SetIamPolicy" in api.mixin_api_methods %} async def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -360,8 +380,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -371,7 +395,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -379,7 +403,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -388,7 +412,7 @@ {% if "GetIamPolicy" in api.mixin_api_methods %} async def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -478,8 +502,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -489,7 +517,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -497,7 +525,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -506,7 +534,7 @@ {% if "TestIamPermissions" in api.mixin_api_methods %} async def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -534,8 +562,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -545,7 +577,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -553,7 +585,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -566,7 +598,7 @@ {% if "GetLocation" in api.mixin_api_methods %} async def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -589,8 +621,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -600,7 +636,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -608,7 +644,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -617,7 +653,7 @@ {% if "ListLocations" in api.mixin_api_methods %} async def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -640,8 +676,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -651,7 +691,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -659,7 +699,7 @@ # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_mixins.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_mixins.py.j2 index 4bfc76e954..4d02f0d91e 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_mixins.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_mixins.py.j2 @@ -3,7 +3,7 @@ {% if "ListOperations" in api.mixin_api_methods %} def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -26,8 +26,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -37,7 +41,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -46,7 +50,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -59,7 +63,7 @@ {% if "GetOperation" in api.mixin_api_methods %} def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -82,8 +86,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -93,7 +101,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -102,7 +110,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -114,7 +122,7 @@ {% if "DeleteOperation" in api.mixin_api_methods %} def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -141,8 +149,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -152,20 +164,20 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "CancelOperation" in api.mixin_api_methods %} def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -191,8 +203,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -202,20 +218,20 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) {% endif %} {% if "WaitOperation" in api.mixin_api_methods %} def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -244,8 +260,12 @@ # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -255,7 +275,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -264,7 +284,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -281,7 +301,7 @@ {% if "SetIamPolicy" in api.mixin_api_methods %} def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -370,8 +390,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -381,7 +405,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -390,7 +414,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -402,7 +426,7 @@ {% if "GetIamPolicy" in api.mixin_api_methods %} def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -492,8 +516,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -503,7 +531,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -512,7 +540,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -524,7 +552,7 @@ {% if "TestIamPermissions" in api.mixin_api_methods %} def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -552,8 +580,12 @@ # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -563,7 +595,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -572,7 +604,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -588,7 +620,7 @@ {% if "GetLocation" in api.mixin_api_methods %} def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -611,8 +643,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -622,7 +658,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -631,7 +667,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -643,7 +679,7 @@ {% if "ListLocations" in api.mixin_api_methods %} def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -666,8 +702,12 @@ # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -677,7 +717,7 @@ # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -686,7 +726,7 @@ try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 index 6db274e82f..2ca7d14756 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 @@ -276,7 +276,7 @@ def _get_http_options(): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/async_client.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/async_client.py.j2 index 689d3e0620..6f712b3b2e 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/async_client.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/async_client.py.j2 @@ -162,7 +162,7 @@ class {{ service.async_client_name }}: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -442,7 +442,7 @@ class {{ service.async_client_name }}: {% if opts.add_iam_methods %} async def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -530,8 +530,12 @@ class {{ service.async_client_name }}: # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -540,21 +544,21 @@ class {{ service.async_client_name }}: # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request_pb.resource),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc(request_pb, 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, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -644,8 +648,12 @@ class {{ service.async_client_name }}: # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -654,21 +662,21 @@ class {{ service.async_client_name }}: # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request_pb.resource),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc(request_pb, 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, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -696,8 +704,12 @@ class {{ service.async_client_name }}: # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -706,14 +718,14 @@ class {{ service.async_client_name }}: # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request_pb.resource),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 0d60f47bb6..e3863159c4 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -143,7 +143,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): This class implements API version {{ service.version }}.{% endif %}""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -151,7 +151,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -161,6 +161,10 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -387,7 +391,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -473,7 +477,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -563,7 +567,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = {{ service.client_name }}._read_environment_variables() self._client_cert_source = {{ service.client_name }}._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = {{ service.client_name }}._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -704,7 +708,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): {% if opts.add_iam_methods %} def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -793,8 +797,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -808,7 +816,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -817,7 +825,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -827,7 +835,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -917,8 +925,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -932,7 +944,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -941,7 +953,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -951,7 +963,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -979,8 +991,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -994,7 +1010,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -1003,7 +1019,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index 11e9e41f3a..1ea30f8e27 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -3,7 +3,7 @@ {% block content %} import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union {% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} from {{package_path}} import gapic_version as package_version @@ -143,6 +143,8 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index 23e7e19839..eb05f151c2 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -76,7 +76,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc_asyncio.py.j2 b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc_asyncio.py.j2 index d5f692442f..7d2994e443 100644 --- a/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc_asyncio.py.j2 +++ b/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc_asyncio.py.j2 @@ -81,7 +81,7 @@ class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pra elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/gapic/templates/noxfile.py.j2 b/gapic/templates/noxfile.py.j2 index 274ca368e0..30fe883868 100644 --- a/gapic/templates/noxfile.py.j2 +++ b/gapic/templates/noxfile.py.j2 @@ -91,8 +91,7 @@ nox.options.error_on_missing_interpreters = True def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -105,6 +104,8 @@ def mypy(session): {% else %} "{{ api.naming.versioned_module_name }}", {% endif %} + "--check-untyped-defs", + *session.posargs, ) diff --git a/gapic/templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 b/gapic/templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 index 169807a961..12e92fa192 100644 --- a/gapic/templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 +++ b/gapic/templates/tests/unit/gapic/%name_%version/%sub/_test_mixins.py.j2 @@ -127,6 +127,41 @@ def test_delete_operation_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): +{% else %} +def test_delete_operation_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = None + + client.delete_operation() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() +{% endfor %} + {% endif %} {# DeleteOperation #} {% if "CancelOperation" in api.mixin_api_methods %} @@ -255,6 +290,41 @@ def test_cancel_operation_from_dict(): {% endif %} call.assert_called() {% endfor %} + +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): +{% else %} +def test_cancel_operation_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = None + + client.cancel_operation() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +{% endfor %} {% endif %} {# CancelOperation #} {% if "WaitOperation" in api.mixin_api_methods %} @@ -384,6 +454,41 @@ def test_wait_operation_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_wait_operation_flattened_async(): +{% else %} +def test_wait_operation_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + {% if mode == "" %} + call.return_value = operations_pb2.Operation() + + client.wait_operation() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.wait_operation() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() +{% endfor %} + {% endif %} {# WaitOperation #} {% if "GetOperation" in api.mixin_api_methods %} @@ -513,6 +618,41 @@ def test_get_operation_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): +{% else %} +def test_get_operation_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = operations_pb2.Operation() + + client.get_operation() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +{% endfor %} + {% endif %} {# GetOperation #} {% if "ListOperations" in api.mixin_api_methods %} @@ -642,6 +782,41 @@ def test_list_operations_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): +{% else %} +def test_list_operations_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +{% endfor %} + {% endif %} {# ListOperations #} {% endif %} {# LRO #} @@ -777,6 +952,41 @@ def test_list_locations_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): +{% else %} +def test_list_locations_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() +{% endfor %} + {% endif %} {# ListLocations #} {# GetLocation #} @@ -907,6 +1117,41 @@ def test_get_location_from_dict(): call.assert_called() {% endfor %} +{% for mode in ["", "async"] %} +{% if mode == "async" %} +@pytest.mark.asyncio +async def test_get_location_flattened_async(): +{% else %} +def test_get_location_flattened(): +{% endif %} + {% if mode == "" %} + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + ) + {% else %} + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + {% endif %} + # 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. + {% if mode == "" %} + call.return_value = locations_pb2.Location() + + client.get_location() + {% else %} + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + {% endif %} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() +{% endfor %} + {% endif %} {# GetLocation #} {% endif %} {# location_mixin #} @@ -1044,6 +1289,43 @@ async def test_set_iam_policy_from_dict_async(): call.assert_called() +def test_set_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + def test_get_iam_policy(transport: str = "grpc"): client = {{ service.client_name }}( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1202,6 +1484,43 @@ async def test_get_iam_policy_from_dict_async(): call.assert_called() +def test_get_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + def test_test_iam_permissions(transport: str = "grpc"): client = {{ service.client_name }}( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1367,6 +1686,43 @@ async def test_test_iam_permissions_from_dict_async(): ) call.assert_called() + +def test_test_iam_permissions_flattened(): + client = {{ service.client_name }}( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.test_iam_permissions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + {% endif %} {% if (not opts.add_iam_methods and api.has_iam_mixin) and ('grpc' in opts.transport or 'grpc_asyncio' in opts.transport) %} @@ -1501,6 +1857,43 @@ async def test_set_iam_policy_from_dict_async(): } ) call.assert_called() + + +def test_set_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() {% endif %} {% if "GetIamPolicy" in api.mixin_api_methods %} @@ -1660,6 +2053,43 @@ async def test_get_iam_policy_from_dict_async(): } ) call.assert_called() + + +def test_get_iam_policy_flattened(): + client = {{ service.client_name }}( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() {% endif %} {% if "TestIamPermissions" in api.mixin_api_methods %} @@ -1827,5 +2257,42 @@ async def test_test_iam_permissions_from_dict_async(): } ) call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = {{ service.client_name }}( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = {{ service.async_client_name }}( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.test_iam_permissions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() {% endif %} {% endif %} diff --git a/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index c0e92cd9d6..3c1d4f7145 100644 --- a/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -146,6 +146,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert {{ service.client_name }}._get_default_mtls_endpoint(None) is None assert {{ service.client_name }}._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -153,6 +154,7 @@ def test__get_default_mtls_endpoint(): assert {{ service.client_name }}._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert {{ service.client_name }}._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert {{ service.client_name }}._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert {{ service.client_name }}._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert {{ service.client_name }}._read_environment_variables() == (False, "auto", None) diff --git a/noxfile.py b/noxfile.py index e99bfad597..4d40c4f979 100644 --- a/noxfile.py +++ b/noxfile.py @@ -607,8 +607,7 @@ def showcase_mypy( """Perform typecheck analysis on the generated Showcase library.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-setuptools", "types-protobuf", "types-requests", @@ -619,7 +618,7 @@ def showcase_mypy( session.chdir(lib) # Run the tests. - session.run("mypy", "-p", "google") + session.run("mypy", "-p", "google", "--check-untyped-defs") @nox.session(python=NEWEST_PYTHON) diff --git a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py index 38379ce9d7..110df677f9 100755 --- a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py +++ b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py @@ -170,7 +170,7 @@ def transport(self) -> AssetServiceTransport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -3154,7 +3154,7 @@ async def sample_analyze_org_policy_governed_assets(): async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3180,8 +3180,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3191,7 +3195,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3199,7 +3203,7 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 843790205a..13571943a3 100755 --- a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -101,7 +101,7 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): """Asset service definition.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -109,7 +109,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -119,6 +119,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -446,7 +450,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -532,7 +536,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -619,7 +623,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AssetServiceClient._read_environment_variables() self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = AssetServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -3576,7 +3580,7 @@ def __exit__(self, type, value, traceback): def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3602,8 +3606,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3613,7 +3621,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3622,7 +3630,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index d1f8c36c11..7636515bcc 100755 --- a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.asset_v1 import gapic_version as package_version @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 1edf735194..feb274eb72 100755 --- a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -55,7 +55,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -86,7 +86,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py index a2b4aeb11a..b833df6e22 100755 --- a/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py +++ b/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -59,7 +59,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -90,7 +90,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/asset/noxfile.py b/tests/integration/goldens/asset/noxfile.py index 487acba725..ef838a250b 100755 --- a/tests/integration/goldens/asset/noxfile.py +++ b/tests/integration/goldens/asset/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index bd17439996..4f8ed36647 100755 --- a/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -114,6 +114,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert AssetServiceClient._get_default_mtls_endpoint(None) is None assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -121,6 +122,7 @@ def test__get_default_mtls_endpoint(): assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert AssetServiceClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert AssetServiceClient._read_environment_variables() == (False, "auto", None) @@ -18385,6 +18387,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = AssetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_transport_close_grpc(): client = AssetServiceClient( diff --git a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py index eac708473c..529bffc55a 100755 --- a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py +++ b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py @@ -161,7 +161,7 @@ def transport(self) -> IAMCredentialsTransport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: diff --git a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 4f2406bad6..db6a2a63fa 100755 --- a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -104,7 +104,7 @@ class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta): """ @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -112,7 +112,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -122,6 +122,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -383,7 +387,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -469,7 +473,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -556,7 +560,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = IAMCredentialsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False diff --git a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index 5eca520ccd..e0c0540c08 100755 --- a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.iam.credentials_v1 import gapic_version as package_version @@ -117,6 +117,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 5baaeb8e5e..6a49e1edff 100755 --- a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -52,7 +52,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -83,7 +83,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py index a793abd09c..4512b4625a 100755 --- a/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py +++ b/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py @@ -56,7 +56,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -87,7 +87,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/credentials/noxfile.py b/tests/integration/goldens/credentials/noxfile.py index af4ba3e285..aff5c15633 100755 --- a/tests/integration/goldens/credentials/noxfile.py +++ b/tests/integration/goldens/credentials/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index d9f2f0a4be..9624eeec05 100755 --- a/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -104,6 +104,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert IAMCredentialsClient._get_default_mtls_endpoint(None) is None assert IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -111,6 +112,7 @@ def test__get_default_mtls_endpoint(): assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert IAMCredentialsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert IAMCredentialsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) diff --git a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py index 09b53be781..06c2fa9dcd 100755 --- a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py +++ b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py @@ -188,7 +188,7 @@ def transport(self) -> EventarcTransport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -2550,7 +2550,7 @@ async def sample_update_google_channel_config(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2576,8 +2576,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2587,7 +2591,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2595,14 +2599,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2628,8 +2632,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2639,7 +2647,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2647,14 +2655,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2684,8 +2692,12 @@ async def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2695,18 +2707,18 @@ async def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2735,8 +2747,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2746,18 +2762,18 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2849,8 +2865,12 @@ async def set_iam_policy( # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2860,7 +2880,7 @@ async def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -2868,14 +2888,14 @@ async def set_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, 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, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2968,8 +2988,12 @@ async def get_iam_policy( # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2979,7 +3003,7 @@ async def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -2987,14 +3011,14 @@ async def get_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, 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, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3025,8 +3049,12 @@ async def test_iam_permissions( # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3036,7 +3064,7 @@ async def test_iam_permissions( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -3044,14 +3072,14 @@ async def test_iam_permissions( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3077,8 +3105,12 @@ async def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3088,7 +3120,7 @@ async def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3096,14 +3128,14 @@ async def get_location( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3129,8 +3161,12 @@ async def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3140,7 +3176,7 @@ async def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3148,7 +3184,7 @@ async def list_locations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 3accde24c6..b0dcd0018d 100755 --- a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -113,7 +113,7 @@ class EventarcClient(metaclass=EventarcClientMeta): """ @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -121,7 +121,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -131,6 +131,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -491,7 +495,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -577,7 +581,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -664,7 +668,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EventarcClient._read_environment_variables() self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = EventarcClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -2997,7 +3001,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3023,8 +3027,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3034,7 +3042,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3043,7 +3051,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3053,7 +3061,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3079,8 +3087,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3090,7 +3102,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3099,7 +3111,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3109,7 +3121,7 @@ def get_operation( def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3139,8 +3151,12 @@ def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3150,18 +3166,18 @@ def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3190,8 +3206,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3201,18 +3221,18 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def set_iam_policy( self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3304,8 +3324,12 @@ def set_iam_policy( # 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) + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3315,7 +3339,7 @@ def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -3324,7 +3348,7 @@ def set_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3334,7 +3358,7 @@ def set_iam_policy( def get_iam_policy( self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3427,8 +3451,12 @@ def get_iam_policy( # 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) + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3438,7 +3466,7 @@ def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -3447,7 +3475,7 @@ def get_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3457,7 +3485,7 @@ def get_iam_policy( def test_iam_permissions( self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3488,8 +3516,12 @@ def test_iam_permissions( # 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) + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3499,7 +3531,7 @@ def test_iam_permissions( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -3508,7 +3540,7 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3518,7 +3550,7 @@ def test_iam_permissions( def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3544,8 +3576,12 @@ def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3555,7 +3591,7 @@ def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3564,7 +3600,7 @@ def get_location( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3574,7 +3610,7 @@ def get_location( def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3600,8 +3636,12 @@ def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3611,7 +3651,7 @@ def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3620,7 +3660,7 @@ def list_locations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index 654a746911..262670647f 100755 --- a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.eventarc_v1 import gapic_version as package_version @@ -128,6 +128,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 887700548d..3f7d58767e 100755 --- a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -63,7 +63,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -94,7 +94,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py index 6c940b3a82..c9c3af6c4f 100755 --- a/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py +++ b/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py @@ -67,7 +67,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -98,7 +98,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/eventarc/noxfile.py b/tests/integration/goldens/eventarc/noxfile.py index c718640903..f4bde8fe92 100755 --- a/tests/integration/goldens/eventarc/noxfile.py +++ b/tests/integration/goldens/eventarc/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 88e728b9ca..8ce71fced4 100755 --- a/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -124,6 +124,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert EventarcClient._get_default_mtls_endpoint(None) is None assert EventarcClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -131,6 +132,7 @@ def test__get_default_mtls_endpoint(): assert EventarcClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert EventarcClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert EventarcClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert EventarcClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert EventarcClient._read_environment_variables() == (False, "auto", None) @@ -16124,6 +16126,37 @@ async def test_delete_operation_from_dict_async(): ) call.assert_called() +def test_delete_operation_flattened(): + client = EventarcClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + def test_cancel_operation(transport: str = "grpc"): client = EventarcClient( @@ -16253,6 +16286,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = EventarcClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = EventarcClient( @@ -16382,6 +16446,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = EventarcClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = EventarcClient( @@ -16511,6 +16606,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = EventarcClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_list_locations(transport: str = "grpc"): client = EventarcClient( @@ -16640,6 +16766,37 @@ async def test_list_locations_from_dict_async(): ) call.assert_called() +def test_list_locations_flattened(): + client = EventarcClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + def test_get_location(transport: str = "grpc"): client = EventarcClient( @@ -16768,6 +16925,37 @@ async def test_get_location_from_dict_async(): ) call.assert_called() +def test_get_location_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + def test_set_iam_policy(transport: str = "grpc"): client = EventarcClient( @@ -16914,6 +17102,43 @@ async def test_set_iam_policy_from_dict_async(): ) call.assert_called() + +def test_set_iam_policy_flattened(): + client = EventarcClient( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + def test_get_iam_policy(transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17071,6 +17296,43 @@ async def test_get_iam_policy_from_dict_async(): ) call.assert_called() + +def test_get_iam_policy_flattened(): + client = EventarcClient( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + def test_test_iam_permissions(transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17237,6 +17499,43 @@ async def test_test_iam_permissions_from_dict_async(): call.assert_called() +def test_test_iam_permissions_flattened(): + client = EventarcClient( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.test_iam_permissions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py index b5d7d26514..668a5f6736 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py @@ -168,7 +168,7 @@ def transport(self) -> ConfigServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -3898,7 +3898,7 @@ async def sample_copy_log_entries(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3924,8 +3924,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3935,7 +3939,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3943,14 +3947,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3976,8 +3980,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3987,7 +3995,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3995,14 +4003,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4031,8 +4039,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4042,14 +4054,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "ConfigServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index b2e701b095..329d5ea9c7 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -97,7 +97,7 @@ class ConfigServiceV2Client(metaclass=ConfigServiceV2ClientMeta): """Service for configuring sinks used to route log entries.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -105,7 +105,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -115,6 +115,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -442,7 +446,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -528,7 +532,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -612,7 +616,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ConfigServiceV2Client._read_environment_variables() self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = ConfigServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -4316,7 +4320,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4342,8 +4346,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4353,7 +4361,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4362,7 +4370,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4372,7 +4380,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4398,8 +4406,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4409,7 +4421,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4418,7 +4430,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4428,7 +4440,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4457,8 +4469,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4468,14 +4484,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index a9ce0fc3ef..8dc5c75947 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index ac3a4393a8..8ad6eaad62 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -55,7 +55,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -86,7 +86,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py index fc7af0c06b..7aacec1ecf 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py @@ -59,7 +59,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -90,7 +90,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py index f84e9f6ec5..0ea020707a 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py @@ -153,7 +153,7 @@ def transport(self) -> LoggingServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -1013,7 +1013,7 @@ def request_generator(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1039,8 +1039,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1050,7 +1054,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1058,14 +1062,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1091,8 +1095,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1102,7 +1110,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1110,14 +1118,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1146,8 +1154,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1157,14 +1169,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "LoggingServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 8c37951cb5..5ea5f377e3 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -94,7 +94,7 @@ class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta): """Service for ingesting and querying logs.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -102,7 +102,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -112,6 +112,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -373,7 +377,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -459,7 +463,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -543,7 +547,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = LoggingServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -1390,7 +1394,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1416,8 +1420,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1427,7 +1435,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1436,7 +1444,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1446,7 +1454,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1472,8 +1480,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1483,7 +1495,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1492,7 +1504,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1502,7 +1514,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1531,8 +1543,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1542,14 +1558,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index d30a4213a5..038531b891 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 8edc617027..86a6f3711d 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -54,7 +54,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -85,7 +85,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py index 92aa1d5256..2dced8c696 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py @@ -58,7 +58,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -89,7 +89,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py index ad659243d7..e03b06353d 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py @@ -154,7 +154,7 @@ def transport(self) -> MetricsServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -864,7 +864,7 @@ async def sample_delete_log_metric(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -890,8 +890,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -901,7 +905,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -909,14 +913,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -942,8 +946,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -953,7 +961,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -961,14 +969,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -997,8 +1005,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1008,14 +1020,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "MetricsServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 6ff3b7ac02..07e388422c 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -95,7 +95,7 @@ class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): """Service for configuring logs-based metrics.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -103,7 +103,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -113,6 +113,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -374,7 +378,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -460,7 +464,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -544,7 +548,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = MetricsServiceV2Client._read_environment_variables() self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = MetricsServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -1241,7 +1245,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1267,8 +1271,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1278,7 +1286,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1287,7 +1295,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1297,7 +1305,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1323,8 +1331,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1334,7 +1346,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1343,7 +1355,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1353,7 +1365,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1382,8 +1394,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1393,14 +1409,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 776ba557f3..454596e3bf 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index d2c41d01e8..37b7ca97be 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -54,7 +54,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -85,7 +85,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py index 15b1ab3ad8..a9344009ed 100755 --- a/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py @@ -58,7 +58,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -89,7 +89,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging/noxfile.py b/tests/integration/goldens/logging/noxfile.py index 8bf90a69f4..5d3bca7cdc 100755 --- a/tests/integration/goldens/logging/noxfile.py +++ b/tests/integration/goldens/logging/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index 9df459055f..2c712a0713 100755 --- a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -105,6 +105,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert ConfigServiceV2Client._get_default_mtls_endpoint(None) is None assert ConfigServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -112,6 +113,7 @@ def test__get_default_mtls_endpoint(): assert ConfigServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert ConfigServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert ConfigServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ConfigServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert ConfigServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -13580,6 +13582,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = ConfigServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = ConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = ConfigServiceV2Client( @@ -13709,6 +13742,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = ConfigServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = ConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = ConfigServiceV2Client( @@ -13838,6 +13902,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = ConfigServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = ConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = ConfigServiceV2Client( diff --git a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 614126cfdb..8963383ef4 100755 --- a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -106,6 +106,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert LoggingServiceV2Client._get_default_mtls_endpoint(None) is None assert LoggingServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -113,6 +114,7 @@ def test__get_default_mtls_endpoint(): assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert LoggingServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert LoggingServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert LoggingServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -3974,6 +3976,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = LoggingServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = LoggingServiceV2Client( @@ -4103,6 +4136,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = LoggingServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = LoggingServiceV2Client( @@ -4232,6 +4296,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = LoggingServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = LoggingServiceV2Client( diff --git a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 027c8ab372..090121a22c 100755 --- a/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -104,6 +104,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert MetricsServiceV2Client._get_default_mtls_endpoint(None) is None assert MetricsServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -111,6 +112,7 @@ def test__get_default_mtls_endpoint(): assert MetricsServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert MetricsServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert MetricsServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert MetricsServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert MetricsServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -3778,6 +3780,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = MetricsServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = MetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = MetricsServiceV2Client( @@ -3907,6 +3940,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = MetricsServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = MetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = MetricsServiceV2Client( @@ -4036,6 +4100,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = MetricsServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = MetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = MetricsServiceV2Client( diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py index ef5a9151a1..405b7cbfa6 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py @@ -168,7 +168,7 @@ def transport(self) -> ConfigServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -3898,7 +3898,7 @@ async def sample_copy_log_entries(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3924,8 +3924,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3935,7 +3939,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3943,14 +3947,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -3976,8 +3980,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -3987,7 +3995,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3995,14 +4003,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4031,8 +4039,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4042,14 +4054,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "BaseConfigServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index 7889ba044b..555d247508 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -97,7 +97,7 @@ class BaseConfigServiceV2Client(metaclass=BaseConfigServiceV2ClientMeta): """Service for configuring sinks used to route log entries.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -105,7 +105,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -115,6 +115,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -442,7 +446,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -528,7 +532,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -612,7 +616,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseConfigServiceV2Client._read_environment_variables() self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = BaseConfigServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -4316,7 +4320,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4342,8 +4346,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4353,7 +4361,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4362,7 +4370,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4372,7 +4380,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4398,8 +4406,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4409,7 +4421,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4418,7 +4430,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4428,7 +4440,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -4457,8 +4469,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -4468,14 +4484,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index a9ce0fc3ef..8dc5c75947 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index ac3a4393a8..8ad6eaad62 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -55,7 +55,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -86,7 +86,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py index fc7af0c06b..7aacec1ecf 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py @@ -59,7 +59,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -90,7 +90,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py index f84e9f6ec5..0ea020707a 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py @@ -153,7 +153,7 @@ def transport(self) -> LoggingServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -1013,7 +1013,7 @@ def request_generator(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1039,8 +1039,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1050,7 +1054,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1058,14 +1062,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1091,8 +1095,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1102,7 +1110,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1110,14 +1118,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1146,8 +1154,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1157,14 +1169,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "LoggingServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 8c37951cb5..5ea5f377e3 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -94,7 +94,7 @@ class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta): """Service for ingesting and querying logs.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -102,7 +102,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -112,6 +112,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -373,7 +377,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -459,7 +463,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -543,7 +547,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = LoggingServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -1390,7 +1394,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1416,8 +1420,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1427,7 +1435,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1436,7 +1444,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1446,7 +1454,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1472,8 +1480,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1483,7 +1495,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1492,7 +1504,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1502,7 +1514,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1531,8 +1543,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1542,14 +1558,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index d30a4213a5..038531b891 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 8edc617027..86a6f3711d 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -54,7 +54,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -85,7 +85,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py index 92aa1d5256..2dced8c696 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py @@ -58,7 +58,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -89,7 +89,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py index 5f0bf0c782..bb936503b4 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py @@ -154,7 +154,7 @@ def transport(self) -> MetricsServiceV2Transport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -864,7 +864,7 @@ async def sample_delete_log_metric(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -890,8 +890,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -901,7 +905,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -909,14 +913,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -942,8 +946,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -953,7 +961,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -961,14 +969,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -997,8 +1005,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1008,14 +1020,14 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def __aenter__(self) -> "BaseMetricsServiceV2AsyncClient": return self diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 479ae7c032..5b98796413 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -95,7 +95,7 @@ class BaseMetricsServiceV2Client(metaclass=BaseMetricsServiceV2ClientMeta): """Service for configuring logs-based metrics.""" @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -103,7 +103,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -113,6 +113,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -374,7 +378,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -460,7 +464,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -544,7 +548,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseMetricsServiceV2Client._read_environment_variables() self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = BaseMetricsServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -1241,7 +1245,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1267,8 +1271,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1278,7 +1286,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1287,7 +1295,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1297,7 +1305,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1323,8 +1331,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1334,7 +1346,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1343,7 +1355,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1353,7 +1365,7 @@ def get_operation( def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1382,8 +1394,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1393,14 +1409,14 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 776ba557f3..454596e3bf 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index d2c41d01e8..37b7ca97be 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -54,7 +54,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -85,7 +85,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py index 15b1ab3ad8..a9344009ed 100755 --- a/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py +++ b/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py @@ -58,7 +58,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -89,7 +89,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/logging_internal/noxfile.py b/tests/integration/goldens/logging_internal/noxfile.py index 8bf90a69f4..5d3bca7cdc 100755 --- a/tests/integration/goldens/logging_internal/noxfile.py +++ b/tests/integration/goldens/logging_internal/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index ca28dea89c..639b54e163 100755 --- a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -105,6 +105,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert BaseConfigServiceV2Client._get_default_mtls_endpoint(None) is None assert BaseConfigServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -112,6 +113,7 @@ def test__get_default_mtls_endpoint(): assert BaseConfigServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert BaseConfigServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert BaseConfigServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert BaseConfigServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert BaseConfigServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -13580,6 +13582,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = BaseConfigServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = BaseConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = BaseConfigServiceV2Client( @@ -13709,6 +13742,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = BaseConfigServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = BaseConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = BaseConfigServiceV2Client( @@ -13838,6 +13902,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = BaseConfigServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = BaseConfigServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = BaseConfigServiceV2Client( diff --git a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 614126cfdb..8963383ef4 100755 --- a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -106,6 +106,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert LoggingServiceV2Client._get_default_mtls_endpoint(None) is None assert LoggingServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -113,6 +114,7 @@ def test__get_default_mtls_endpoint(): assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert LoggingServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert LoggingServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert LoggingServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -3974,6 +3976,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = LoggingServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = LoggingServiceV2Client( @@ -4103,6 +4136,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = LoggingServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = LoggingServiceV2Client( @@ -4232,6 +4296,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = LoggingServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = LoggingServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = LoggingServiceV2Client( diff --git a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index d843efe3c1..ab32958b3f 100755 --- a/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -104,6 +104,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(None) is None assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -111,6 +112,7 @@ def test__get_default_mtls_endpoint(): assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert BaseMetricsServiceV2Client._read_environment_variables() == (False, "auto", None) @@ -3778,6 +3780,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = BaseMetricsServiceV2Client( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = BaseMetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_get_operation(transport: str = "grpc"): client = BaseMetricsServiceV2Client( @@ -3907,6 +3940,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = BaseMetricsServiceV2Client( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = BaseMetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = BaseMetricsServiceV2Client( @@ -4036,6 +4100,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = BaseMetricsServiceV2Client( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = BaseMetricsServiceV2AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_transport_close_grpc(): client = BaseMetricsServiceV2Client( diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py index ea3e960a8e..f496a43c8b 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -178,7 +178,7 @@ def transport(self) -> CloudRedisTransport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -1771,7 +1771,7 @@ async def sample_reschedule_maintenance(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1797,8 +1797,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1808,7 +1812,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1816,14 +1820,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1849,8 +1853,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1860,7 +1868,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1868,14 +1876,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1905,8 +1913,12 @@ async def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1916,18 +1928,18 @@ async def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1956,8 +1968,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1967,18 +1983,18 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2010,8 +2026,12 @@ async def wait_operation( # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2021,7 +2041,7 @@ async def wait_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2029,14 +2049,14 @@ async def wait_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2062,8 +2082,12 @@ async def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2073,7 +2097,7 @@ async def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2081,14 +2105,14 @@ async def get_location( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2114,8 +2138,12 @@ async def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2125,7 +2153,7 @@ async def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2133,7 +2161,7 @@ async def list_locations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index f3da10c2fc..f17dc10e34 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -131,7 +131,7 @@ class CloudRedisClient(metaclass=CloudRedisClientMeta): """ @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -139,7 +139,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -149,6 +149,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -410,7 +414,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -496,7 +500,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -583,7 +587,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = CloudRedisClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -2176,7 +2180,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2202,8 +2206,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2213,7 +2221,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2222,7 +2230,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2232,7 +2240,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2258,8 +2266,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2269,7 +2281,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2278,7 +2290,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2288,7 +2300,7 @@ def get_operation( def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2318,8 +2330,12 @@ def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2329,18 +2345,18 @@ def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2369,8 +2385,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2380,18 +2400,18 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2423,8 +2443,12 @@ def wait_operation( # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2434,7 +2458,7 @@ def wait_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2443,7 +2467,7 @@ def wait_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2453,7 +2477,7 @@ def wait_operation( def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2479,8 +2503,12 @@ def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2490,7 +2518,7 @@ def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2499,7 +2527,7 @@ def get_location( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2509,7 +2537,7 @@ def get_location( def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -2535,8 +2563,12 @@ def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2546,7 +2578,7 @@ def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2555,7 +2587,7 @@ def list_locations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 54f7d694a3..78e44f7381 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.redis_v1 import gapic_version as package_version @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index ac164835f5..a460cbb67b 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -55,7 +55,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -86,7 +86,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py index 46f96b5c5c..692cd77d36 100755 --- a/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py +++ b/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py @@ -59,7 +59,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -90,7 +90,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/redis/noxfile.py b/tests/integration/goldens/redis/noxfile.py index 4349f5147d..2b6cbd1280 100755 --- a/tests/integration/goldens/redis/noxfile.py +++ b/tests/integration/goldens/redis/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index ae66b5a92c..255358ee2a 100755 --- a/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -122,6 +122,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert CloudRedisClient._get_default_mtls_endpoint(None) is None assert CloudRedisClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -129,6 +130,7 @@ def test__get_default_mtls_endpoint(): assert CloudRedisClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert CloudRedisClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert CloudRedisClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert CloudRedisClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert CloudRedisClient._read_environment_variables() == (False, "auto", None) @@ -12222,6 +12224,37 @@ async def test_delete_operation_from_dict_async(): ) call.assert_called() +def test_delete_operation_flattened(): + client = CloudRedisClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + def test_cancel_operation(transport: str = "grpc"): client = CloudRedisClient( @@ -12351,6 +12384,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = CloudRedisClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_wait_operation(transport: str = "grpc"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12479,6 +12543,37 @@ async def test_wait_operation_from_dict_async(): ) call.assert_called() +def test_wait_operation_flattened(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.wait_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() +@pytest.mark.asyncio +async def test_wait_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.wait_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() + def test_get_operation(transport: str = "grpc"): client = CloudRedisClient( @@ -12608,6 +12703,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = CloudRedisClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = CloudRedisClient( @@ -12737,6 +12863,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = CloudRedisClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_list_locations(transport: str = "grpc"): client = CloudRedisClient( @@ -12866,6 +13023,37 @@ async def test_list_locations_from_dict_async(): ) call.assert_called() +def test_list_locations_flattened(): + client = CloudRedisClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + def test_get_location(transport: str = "grpc"): client = CloudRedisClient( @@ -12994,6 +13182,37 @@ async def test_get_location_from_dict_async(): ) call.assert_called() +def test_get_location_flattened(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + def test_transport_close_grpc(): client = CloudRedisClient( diff --git a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py index 6e826449ce..e703d95677 100755 --- a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -178,7 +178,7 @@ def transport(self) -> CloudRedisTransport: return self._client.transport @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -964,7 +964,7 @@ async def sample_delete_instance(): async def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -990,8 +990,12 @@ async def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1001,7 +1005,7 @@ async def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1009,14 +1013,14 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1042,8 +1046,12 @@ async def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1053,7 +1061,7 @@ async def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1061,14 +1069,14 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1098,8 +1106,12 @@ async def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1109,18 +1121,18 @@ async def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1149,8 +1161,12 @@ async def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1160,18 +1176,18 @@ async def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) async def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1203,8 +1219,12 @@ async def wait_operation( # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1214,7 +1234,7 @@ async def wait_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1222,14 +1242,14 @@ async def wait_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1255,8 +1275,12 @@ async def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1266,7 +1290,7 @@ async def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1274,14 +1298,14 @@ async def get_location( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response async def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1307,8 +1331,12 @@ async def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1318,7 +1346,7 @@ async def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1326,7 +1354,7 @@ async def list_locations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 32c43e15f1..b3ad484bc1 100755 --- a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -131,7 +131,7 @@ class CloudRedisClient(metaclass=CloudRedisClientMeta): """ @staticmethod - def _get_default_mtls_endpoint(api_endpoint): + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -139,7 +139,7 @@ def _get_default_mtls_endpoint(api_endpoint): Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: - str: converted mTLS api endpoint. + Optional[str]: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint @@ -149,6 +149,10 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # could not parse api_endpoint; return as-is + return api_endpoint + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -410,7 +414,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -496,7 +500,7 @@ def _add_cred_info_for_auth_errors( error._details.append(json.dumps(cred_info)) @property - def api_endpoint(self): + def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. Returns: @@ -583,7 +587,7 @@ def __init__(self, *, self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = CloudRedisClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -1375,7 +1379,7 @@ def __exit__(self, type, value, traceback): def list_operations( self, - request: Optional[operations_pb2.ListOperationsRequest] = None, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1401,8 +1405,12 @@ def list_operations( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1412,7 +1420,7 @@ def list_operations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1421,7 +1429,7 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1431,7 +1439,7 @@ def list_operations( def get_operation( self, - request: Optional[operations_pb2.GetOperationRequest] = None, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1457,8 +1465,12 @@ def get_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1468,7 +1480,7 @@ def get_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1477,7 +1489,7 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1487,7 +1499,7 @@ def get_operation( def delete_operation( self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1517,8 +1529,12 @@ def delete_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1528,18 +1544,18 @@ def delete_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, - request: Optional[operations_pb2.CancelOperationRequest] = None, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1568,8 +1584,12 @@ def cancel_operation( # Create or coerce a protobuf 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) + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1579,18 +1599,18 @@ def cancel_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def wait_operation( self, - request: Optional[operations_pb2.WaitOperationRequest] = None, + request: Optional[Union[operations_pb2.WaitOperationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1622,8 +1642,12 @@ def wait_operation( # Create or coerce a protobuf 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.WaitOperationRequest(**request) + if request is None: + request_pb = operations_pb2.WaitOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.WaitOperationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1633,7 +1657,7 @@ def wait_operation( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1642,7 +1666,7 @@ def wait_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1652,7 +1676,7 @@ def wait_operation( def get_location( self, - request: Optional[locations_pb2.GetLocationRequest] = None, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1678,8 +1702,12 @@ def get_location( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1689,7 +1717,7 @@ def get_location( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1698,7 +1726,7 @@ def get_location( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1708,7 +1736,7 @@ def get_location( def list_locations( self, - request: Optional[locations_pb2.ListLocationsRequest] = None, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, @@ -1734,8 +1762,12 @@ def list_locations( # Create or coerce a protobuf 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) + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1745,7 +1777,7 @@ def list_locations( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1754,7 +1786,7 @@ def list_locations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response diff --git a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index c442745a86..5ae62e8af2 100755 --- a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -14,7 +14,7 @@ # limitations under the License. # import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.redis_v1 import gapic_version as package_version @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable[..., Any], Callable[..., Any]] = {} + @property def host(self): return self._host diff --git a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index fe65a8baf8..3e9ec3b573 100755 --- a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -55,7 +55,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -86,7 +86,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py index a3393990f2..de6f824f30 100755 --- a/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py +++ b/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py @@ -59,7 +59,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(request, google.protobuf.message.Message): request_payload = MessageToJson(request) else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" request_metadata = { key: value.decode("utf-8") if isinstance(value, bytes) else value @@ -90,7 +90,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request elif isinstance(result, google.protobuf.message.Message): response_payload = MessageToJson(result) else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" grpc_response = { "payload": response_payload, "metadata": metadata, diff --git a/tests/integration/goldens/redis_selective/noxfile.py b/tests/integration/goldens/redis_selective/noxfile.py index 4349f5147d..2b6cbd1280 100755 --- a/tests/integration/goldens/redis_selective/noxfile.py +++ b/tests/integration/goldens/redis_selective/noxfile.py @@ -98,8 +98,7 @@ def mypy(session): """Run the type checker.""" session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", + "mypy", "types-requests", "types-protobuf", ) @@ -108,6 +107,8 @@ def mypy(session): "mypy", "-p", "google", + "--check-untyped-defs", + *session.posargs, ) diff --git a/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 44403c6627..1b85188c8a 100755 --- a/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -122,6 +122,7 @@ def test__get_default_mtls_endpoint(): sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" + custom_endpoint = ".custom" assert CloudRedisClient._get_default_mtls_endpoint(None) is None assert CloudRedisClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -129,6 +130,7 @@ def test__get_default_mtls_endpoint(): assert CloudRedisClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert CloudRedisClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert CloudRedisClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert CloudRedisClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert CloudRedisClient._read_environment_variables() == (False, "auto", None) @@ -7388,6 +7390,37 @@ async def test_delete_operation_from_dict_async(): ) call.assert_called() +def test_delete_operation_flattened(): + client = CloudRedisClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + def test_cancel_operation(transport: str = "grpc"): client = CloudRedisClient( @@ -7517,6 +7550,37 @@ async def test_cancel_operation_from_dict_async(): ) call.assert_called() +def test_cancel_operation_flattened(): + client = CloudRedisClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + def test_wait_operation(transport: str = "grpc"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7645,6 +7709,37 @@ async def test_wait_operation_from_dict_async(): ) call.assert_called() +def test_wait_operation_flattened(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.wait_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() +@pytest.mark.asyncio +async def test_wait_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.wait_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.WaitOperationRequest() + def test_get_operation(transport: str = "grpc"): client = CloudRedisClient( @@ -7774,6 +7869,37 @@ async def test_get_operation_from_dict_async(): ) call.assert_called() +def test_get_operation_flattened(): + client = CloudRedisClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + def test_list_operations(transport: str = "grpc"): client = CloudRedisClient( @@ -7903,6 +8029,37 @@ async def test_list_operations_from_dict_async(): ) call.assert_called() +def test_list_operations_flattened(): + client = CloudRedisClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + def test_list_locations(transport: str = "grpc"): client = CloudRedisClient( @@ -8032,6 +8189,37 @@ async def test_list_locations_from_dict_async(): ) call.assert_called() +def test_list_locations_flattened(): + client = CloudRedisClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + def test_get_location(transport: str = "grpc"): client = CloudRedisClient( @@ -8160,6 +8348,37 @@ async def test_get_location_from_dict_async(): ) call.assert_called() +def test_get_location_flattened(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + def test_transport_close_grpc(): client = CloudRedisClient(