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..d76aa97d06 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..53db8ed5ef 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 @@ -98,6 +98,8 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + # 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 a4d13c34b9..81c9a11a07 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 @@ -277,7 +277,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 c5abf93ed6..a77c92f36b 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 @@ -164,7 +164,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: @@ -444,7 +444,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, @@ -532,8 +532,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. @@ -542,21 +546,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, @@ -646,8 +650,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. @@ -656,21 +664,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, @@ -698,8 +706,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. @@ -708,14 +720,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..f8056c05c7 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 08c02448b6..030c74592a 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 @@ -143,6 +143,8 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 c03635deb5..832e464079 100644 --- a/gapic/templates/noxfile.py.j2 +++ b/gapic/templates/noxfile.py.j2 @@ -90,8 +90,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", ) @@ -104,6 +103,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 78f5ad469d..0a48dd6e18 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 @@ -147,6 +147,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 @@ -154,6 +155,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 d45bbdc876..95aa2ad6fe 100644 --- a/noxfile.py +++ b/noxfile.py @@ -609,8 +609,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", @@ -621,7 +620,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 6671f3a75f..d99a72b341 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 @@ -172,7 +172,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: @@ -3156,7 +3156,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, @@ -3182,8 +3182,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. @@ -3193,7 +3197,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. @@ -3201,7 +3205,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 79fb1058cb..340315ad89 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 dedcdb2f0b..2b506901a2 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 @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 daa6a60e7e..ffc4a7dd7d 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 ef1bd83e28..40927a0d0a 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 3005dac3c7..4020695367 100755 --- a/tests/integration/goldens/asset/noxfile.py +++ b/tests/integration/goldens/asset/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 ca243f67aa..d3b9bbf528 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 @@ -115,6 +115,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 @@ -122,6 +123,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) @@ -18386,6 +18388,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 47e6150e3f..070f351dfe 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 @@ -163,7 +163,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 a3a6f84e33..c55d4a2a44 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..4bd2513c12 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 @@ -117,6 +117,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 1b63a5d05d..0e75c09485 100755 --- a/tests/integration/goldens/credentials/noxfile.py +++ b/tests/integration/goldens/credentials/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 7f145edd40..fa2116cdd7 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 @@ -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 IAMCredentialsClient._get_default_mtls_endpoint(None) is None assert IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -112,6 +113,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 dbb6896c41..74cfbce551 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 @@ -190,7 +190,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: @@ -2552,7 +2552,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, @@ -2578,8 +2578,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. @@ -2589,7 +2593,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. @@ -2597,14 +2601,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, @@ -2630,8 +2634,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. @@ -2641,7 +2649,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. @@ -2649,14 +2657,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, @@ -2686,8 +2694,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. @@ -2697,18 +2709,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, @@ -2737,8 +2749,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. @@ -2748,18 +2764,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, @@ -2851,8 +2867,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. @@ -2862,7 +2882,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. @@ -2870,14 +2890,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, @@ -2970,8 +2990,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. @@ -2981,7 +3005,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. @@ -2989,14 +3013,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, @@ -3027,8 +3051,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. @@ -3038,7 +3066,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. @@ -3046,14 +3074,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, @@ -3079,8 +3107,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. @@ -3090,7 +3122,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. @@ -3098,14 +3130,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, @@ -3131,8 +3163,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. @@ -3142,7 +3178,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. @@ -3150,7 +3186,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 b190ba2f34..0e79129eaa 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..69ebf3a8d2 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 @@ -128,6 +128,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 235454ee92..82c7fc681e 100755 --- a/tests/integration/goldens/eventarc/noxfile.py +++ b/tests/integration/goldens/eventarc/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 0f51ab3838..95f5228fba 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 @@ -125,6 +125,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 @@ -132,6 +133,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) @@ -16125,6 +16127,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( @@ -16254,6 +16287,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( @@ -16383,6 +16447,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( @@ -16512,6 +16607,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( @@ -16641,6 +16767,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( @@ -16769,6 +16926,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( @@ -16915,6 +17103,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, @@ -17072,6 +17297,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, @@ -17238,6 +17500,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 0a88964f2a..d84883919a 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 @@ -170,7 +170,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: @@ -3900,7 +3900,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, @@ -3926,8 +3926,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. @@ -3937,7 +3941,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. @@ -3945,14 +3949,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, @@ -3978,8 +3982,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. @@ -3989,7 +3997,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. @@ -3997,14 +4005,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, @@ -4033,8 +4041,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. @@ -4044,14 +4056,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 1dc177afa6..c3e16949aa 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 a54da26717..5d24faa404 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 c178350462..cccf46fb03 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 85199473c0..474cf06a45 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 b2f472a6d0..a20654de2c 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 @@ -155,7 +155,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: @@ -1015,7 +1015,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, @@ -1041,8 +1041,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. @@ -1052,7 +1056,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. @@ -1060,14 +1064,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, @@ -1093,8 +1097,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. @@ -1104,7 +1112,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. @@ -1112,14 +1120,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, @@ -1148,8 +1156,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. @@ -1159,14 +1171,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 7080ae8c84..ea794ebe36 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 d3eb7d5bd5..1ed98c63a1 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 7a0f637c92..d0b3d6aad7 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 da2030c510..22e7dfeffc 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 6932957dc9..8ac9536a12 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 @@ -156,7 +156,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: @@ -866,7 +866,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, @@ -892,8 +892,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. @@ -903,7 +907,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. @@ -911,14 +915,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, @@ -944,8 +948,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. @@ -955,7 +963,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. @@ -963,14 +971,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, @@ -999,8 +1007,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. @@ -1010,14 +1022,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 e17a68536b..cb17f9cf26 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 6c9441cc02..15b1901d48 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 0a6c2a5282..047afa95b9 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 7f88d30b76..b601346f6e 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 c2efe83be4..7ae67c9a5e 100755 --- a/tests/integration/goldens/logging/noxfile.py +++ b/tests/integration/goldens/logging/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 2e5a4bf1ea..df852b3966 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 @@ -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 ConfigServiceV2Client._get_default_mtls_endpoint(None) is None assert ConfigServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -113,6 +114,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) @@ -13581,6 +13583,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( @@ -13710,6 +13743,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( @@ -13839,6 +13903,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 f5b0e03c67..004308fbe8 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 @@ -107,6 +107,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 @@ -114,6 +115,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) @@ -3975,6 +3977,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( @@ -4104,6 +4137,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( @@ -4233,6 +4297,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 eced7f0f49..2ba63c9b56 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 @@ -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 MetricsServiceV2Client._get_default_mtls_endpoint(None) is None assert MetricsServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -112,6 +113,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) @@ -3779,6 +3781,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( @@ -3908,6 +3941,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( @@ -4037,6 +4101,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 82ba68904f..3f9bd2ddae 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 @@ -170,7 +170,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: @@ -3900,7 +3900,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, @@ -3926,8 +3926,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. @@ -3937,7 +3941,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. @@ -3945,14 +3949,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, @@ -3978,8 +3982,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. @@ -3989,7 +3997,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. @@ -3997,14 +4005,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, @@ -4033,8 +4041,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. @@ -4044,14 +4056,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 8d2c2149d4..a597989ec5 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 a54da26717..5d24faa404 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 c178350462..cccf46fb03 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 85199473c0..474cf06a45 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 b2f472a6d0..a20654de2c 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 @@ -155,7 +155,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: @@ -1015,7 +1015,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, @@ -1041,8 +1041,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. @@ -1052,7 +1056,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. @@ -1060,14 +1064,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, @@ -1093,8 +1097,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. @@ -1104,7 +1112,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. @@ -1112,14 +1120,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, @@ -1148,8 +1156,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. @@ -1159,14 +1171,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 7080ae8c84..ea794ebe36 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 d3eb7d5bd5..1ed98c63a1 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 7a0f637c92..d0b3d6aad7 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 da2030c510..22e7dfeffc 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 69751fc378..765633f4b8 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 @@ -156,7 +156,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: @@ -866,7 +866,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, @@ -892,8 +892,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. @@ -903,7 +907,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. @@ -911,14 +915,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, @@ -944,8 +948,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. @@ -955,7 +963,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. @@ -963,14 +971,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, @@ -999,8 +1007,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. @@ -1010,14 +1022,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 ef25218bc1..c83b00ecb0 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 6c9441cc02..15b1901d48 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 @@ -123,6 +123,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 0a6c2a5282..047afa95b9 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 7f88d30b76..b601346f6e 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 c2efe83be4..7ae67c9a5e 100755 --- a/tests/integration/goldens/logging_internal/noxfile.py +++ b/tests/integration/goldens/logging_internal/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 8720112bed..ab7c4d61dd 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 @@ -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 BaseConfigServiceV2Client._get_default_mtls_endpoint(None) is None assert BaseConfigServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -113,6 +114,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) @@ -13581,6 +13583,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( @@ -13710,6 +13743,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( @@ -13839,6 +13903,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 f5b0e03c67..004308fbe8 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 @@ -107,6 +107,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 @@ -114,6 +115,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) @@ -3975,6 +3977,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( @@ -4104,6 +4137,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( @@ -4233,6 +4297,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 33f3e8e104..caf4c92c6d 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 @@ -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 BaseMetricsServiceV2Client._get_default_mtls_endpoint(None) is None assert BaseMetricsServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint @@ -112,6 +113,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) @@ -3779,6 +3781,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( @@ -3908,6 +3941,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( @@ -4037,6 +4101,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 78f428b8ec..43f13c7c8f 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 @@ -180,7 +180,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: @@ -1773,7 +1773,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, @@ -1799,8 +1799,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. @@ -1810,7 +1814,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. @@ -1818,14 +1822,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, @@ -1851,8 +1855,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. @@ -1862,7 +1870,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. @@ -1870,14 +1878,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, @@ -1907,8 +1915,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. @@ -1918,18 +1930,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, @@ -1958,8 +1970,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. @@ -1969,18 +1985,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, @@ -2012,8 +2028,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. @@ -2023,7 +2043,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. @@ -2031,14 +2051,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, @@ -2064,8 +2084,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. @@ -2075,7 +2099,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. @@ -2083,14 +2107,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, @@ -2116,8 +2140,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. @@ -2127,7 +2155,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. @@ -2135,7 +2163,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 a21a9fd930..e03925e7f3 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..33836f7155 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 @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 0291767b81..515584fb61 100755 --- a/tests/integration/goldens/redis/noxfile.py +++ b/tests/integration/goldens/redis/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 3f3dafe4de..572db4b7ab 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 @@ -123,6 +123,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 @@ -130,6 +131,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) @@ -12223,6 +12225,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( @@ -12352,6 +12385,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, @@ -12480,6 +12544,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( @@ -12609,6 +12704,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( @@ -12738,6 +12864,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( @@ -12867,6 +13024,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( @@ -12995,6 +13183,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 5dc91b1bd8..adfdbc5559 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 @@ -180,7 +180,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: @@ -966,7 +966,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, @@ -992,8 +992,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. @@ -1003,7 +1007,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. @@ -1011,14 +1015,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, @@ -1044,8 +1048,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. @@ -1055,7 +1063,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. @@ -1063,14 +1071,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, @@ -1100,8 +1108,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. @@ -1111,18 +1123,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, @@ -1151,8 +1163,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. @@ -1162,18 +1178,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, @@ -1205,8 +1221,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. @@ -1216,7 +1236,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. @@ -1224,14 +1244,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, @@ -1257,8 +1277,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. @@ -1268,7 +1292,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. @@ -1276,14 +1300,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, @@ -1309,8 +1333,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. @@ -1320,7 +1348,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. @@ -1328,7 +1356,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 b8a18ffd5e..efaccae55c 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..3feba74209 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 @@ -120,6 +120,8 @@ def __init__( host += ':443' self._host = host + self._wrapped_methods: Dict[Callable, Callable] = {} + @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 0291767b81..515584fb61 100755 --- a/tests/integration/goldens/redis_selective/noxfile.py +++ b/tests/integration/goldens/redis_selective/noxfile.py @@ -97,8 +97,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", ) @@ -107,6 +106,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 da97232fb4..f4079c0ee6 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 @@ -123,6 +123,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 @@ -130,6 +131,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) @@ -7389,6 +7391,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( @@ -7518,6 +7551,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, @@ -7646,6 +7710,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( @@ -7775,6 +7870,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( @@ -7904,6 +8030,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( @@ -8033,6 +8190,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( @@ -8161,6 +8349,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(