1# Copyright 2018 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Tests 'utf-8' encoded error message.""" 15 16import unittest 17import weakref 18 19import grpc 20 21from tests.unit import test_common 22from tests.unit.framework.common import test_constants 23 24_UNICODE_ERROR_MESSAGES = [ 25 b"\xe2\x80\x9d".decode("utf-8"), 26 b"abc\x80\xd0\xaf".decode("latin-1"), 27 b"\xc3\xa9".decode("utf-8"), 28] 29 30_REQUEST = b"\x00\x00\x00" 31_RESPONSE = b"\x00\x00\x00" 32 33_UNARY_UNARY = "/test/UnaryUnary" 34 35 36class _MethodHandler(grpc.RpcMethodHandler): 37 def __init__(self, request_streaming=None, response_streaming=None): 38 self.request_streaming = request_streaming 39 self.response_streaming = response_streaming 40 self.request_deserializer = None 41 self.response_serializer = None 42 self.unary_stream = None 43 self.stream_unary = None 44 self.stream_stream = None 45 46 def unary_unary(self, request, servicer_context): 47 servicer_context.set_code(grpc.StatusCode.UNKNOWN) 48 servicer_context.set_details(request.decode("utf-8")) 49 return _RESPONSE 50 51 52class _GenericHandler(grpc.GenericRpcHandler): 53 def __init__(self, test): 54 self._test = test 55 56 def service(self, handler_call_details): 57 return _MethodHandler() 58 59 60class ErrorMessageEncodingTest(unittest.TestCase): 61 def setUp(self): 62 self._server = test_common.test_server() 63 self._server.add_generic_rpc_handlers( 64 (_GenericHandler(weakref.proxy(self)),) 65 ) 66 port = self._server.add_insecure_port("[::]:0") 67 self._server.start() 68 self._channel = grpc.insecure_channel("localhost:%d" % port) 69 70 def tearDown(self): 71 self._server.stop(0) 72 self._channel.close() 73 74 def testMessageEncoding(self): 75 for message in _UNICODE_ERROR_MESSAGES: 76 multi_callable = self._channel.unary_unary( 77 _UNARY_UNARY, 78 _registered_method=True, 79 ) 80 with self.assertRaises(grpc.RpcError) as cm: 81 multi_callable(message.encode("utf-8")) 82 83 self.assertEqual(cm.exception.code(), grpc.StatusCode.UNKNOWN) 84 self.assertEqual(cm.exception.details(), message) 85 86 87if __name__ == "__main__": 88 unittest.main(verbosity=2) 89