• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 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 that a channel will reconnect if a connection is dropped"""
15
16import logging
17import socket
18import time
19import unittest
20
21import grpc
22from grpc.framework.foundation import logging_pool
23
24from tests.unit.framework.common import bound_socket
25from tests.unit.framework.common import test_constants
26
27_REQUEST = b"\x00\x00\x00"
28_RESPONSE = b"\x00\x00\x01"
29
30_UNARY_UNARY = "/test/UnaryUnary"
31
32
33def _handle_unary_unary(unused_request, unused_servicer_context):
34    return _RESPONSE
35
36
37class ReconnectTest(unittest.TestCase):
38    def test_reconnect(self):
39        server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
40        handler = grpc.method_handlers_generic_handler(
41            "test",
42            {
43                "UnaryUnary": grpc.unary_unary_rpc_method_handler(
44                    _handle_unary_unary
45                )
46            },
47        )
48        options = (("grpc.so_reuseport", 1),)
49        with bound_socket() as (host, port):
50            addr = "{}:{}".format(host, port)
51            server = grpc.server(server_pool, (handler,), options=options)
52            server.add_insecure_port(addr)
53            server.start()
54        channel = grpc.insecure_channel(addr)
55        multi_callable = channel.unary_unary(
56            _UNARY_UNARY,
57            _registered_method=True,
58        )
59        self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
60        server.stop(None)
61        # By default, the channel connectivity is checked every 5s
62        # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change
63        # this.
64        time.sleep(5.1)
65        server = grpc.server(server_pool, (handler,), options=options)
66        server.add_insecure_port(addr)
67        server.start()
68        self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
69        server.stop(None)
70        channel.close()
71
72
73if __name__ == "__main__":
74    logging.basicConfig()
75    unittest.main(verbosity=2)
76