• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_SERVICE_NAME = "test"
34_UNARY_UNARY = "UnaryUnary"
35
36
37class _MethodHandler(grpc.RpcMethodHandler):
38    def __init__(self, request_streaming=None, response_streaming=None):
39        self.request_streaming = request_streaming
40        self.response_streaming = response_streaming
41        self.request_deserializer = None
42        self.response_serializer = None
43        self.unary_stream = None
44        self.stream_unary = None
45        self.stream_stream = None
46
47    def unary_unary(self, request, servicer_context):
48        servicer_context.set_code(grpc.StatusCode.UNKNOWN)
49        servicer_context.set_details(request.decode("utf-8"))
50        return _RESPONSE
51
52
53_METHOD_HANDLERS = {_UNARY_UNARY: _MethodHandler()}
54
55
56class ErrorMessageEncodingTest(unittest.TestCase):
57    def setUp(self):
58        self._server = test_common.test_server()
59        self._server.add_registered_method_handlers(
60            _SERVICE_NAME, _METHOD_HANDLERS
61        )
62        port = self._server.add_insecure_port("[::]:0")
63        self._server.start()
64        self._channel = grpc.insecure_channel("localhost:%d" % port)
65
66    def tearDown(self):
67        self._server.stop(0)
68        self._channel.close()
69
70    def testMessageEncoding(self):
71        for message in _UNICODE_ERROR_MESSAGES:
72            multi_callable = self._channel.unary_unary(
73                grpc._common.fully_qualified_method(
74                    _SERVICE_NAME, _UNARY_UNARY
75                ),
76                _registered_method=True,
77            )
78            with self.assertRaises(grpc.RpcError) as cm:
79                multi_callable(message.encode("utf-8"))
80
81            self.assertEqual(cm.exception.code(), grpc.StatusCode.UNKNOWN)
82            self.assertEqual(cm.exception.details(), message)
83
84
85if __name__ == "__main__":
86    unittest.main(verbosity=2)
87