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 socket 17import time 18import logging 19import unittest 20 21import grpc 22from grpc.framework.foundation import logging_pool 23 24from tests.unit.framework.common import test_constants 25from tests.unit.framework.common import bound_socket 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 39 def test_reconnect(self): 40 server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY) 41 handler = grpc.method_handlers_generic_handler('test', { 42 'UnaryUnary': 43 grpc.unary_unary_rpc_method_handler(_handle_unary_unary) 44 }) 45 options = (('grpc.so_reuseport', 1),) 46 with bound_socket() as (host, port): 47 addr = '{}:{}'.format(host, port) 48 server = grpc.server(server_pool, (handler,), options=options) 49 server.add_insecure_port(addr) 50 server.start() 51 channel = grpc.insecure_channel(addr) 52 multi_callable = channel.unary_unary(_UNARY_UNARY) 53 self.assertEqual(_RESPONSE, multi_callable(_REQUEST)) 54 server.stop(None) 55 # By default, the channel connectivity is checked every 5s 56 # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change 57 # this. 58 time.sleep(5.1) 59 server = grpc.server(server_pool, (handler,), options=options) 60 server.add_insecure_port(addr) 61 server.start() 62 self.assertEqual(_RESPONSE, multi_callable(_REQUEST)) 63 server.stop(None) 64 channel.close() 65 66 67if __name__ == '__main__': 68 logging.basicConfig() 69 unittest.main(verbosity=2) 70