Tornado的WebSocketClientConnection的close方法不会调用Websocket Handler的on_close方法

时间:2015-12-01 11:49:23

标签: python websocket tornado

我有一个像这样的WebsocketHandler:

class MyHandler(WebSocketHandler):

    def open(self, *args, **kwargs):
        self.application.logger.info('WebSocket connection opened from %s', self.request.remote_ip)

    def on_close(self):
        self.application.logger.info('WebSocket connection closed')

    def on_message(self, message):
        self.write_message(message)

我使用pytest进行了一些测试:

@pytest.fixture
def app(request):
    request.cls.app_fixture = create_app(TornadoConfig)


@pytest.mark.usefixtures("app")
class TestWebSocket(testing.AsyncHTTPTestCase):

    def get_app(self):
        return self.app_fixture

    def setUp(self):
        super(TestWebSocket, self).setUp()
        server = httpserver.HTTPServer(self.app_fixture)
        self.socket, self.port = testing.bind_unused_port()
        server.add_socket(self.socket)

    def _mk_client(self):
        client = websocket_connect('ws://localhost:{}/ws/'.format(self.port))
        TestWebSocket.clients.append(client)
        return client

    @testing.gen_test
    def test_auto_complete(self):
       client = yield self._mk_client()
       client.write_message('test')
       response = yield client.read_message()

       assert response == 'test'

       client.close()

虽然我跟踪了它,但我确信调用了close方法,但client.close()MyHandler没有任何影响,on_close永远不会被调用!

2 个答案:

答案 0 :(得分:1)

client.close() 导致MyHandler.on_close被调用,但它还没有,当测试方法返回时,它永远不会有机会。如果您想确保调用on_close,则必须等待on_close被调用,而不是在client.close()返回后立即返回。例如,参见Tornado对websocket功能的测试:https://github.com/tornadoweb/tornado/blob/43e23f977715396ce243c6cd7e3387abf2a2e4ee/tornado/test/websocket_test.py#L44

答案 1 :(得分:-1)

我使用ThreadPoolExecutor来解决我的问题 所以我创建了一个thread_pool

thread_pool = ThreadPoolExecutor(1)

并编写了另一种方法来关闭客户端的连接:

def close_ws(self, client):
    client.close()
    time.sleep(1)
    self.close_future.set_result('done')

在测试方法结束时我做了:

self.thread_pool.submit(self.close_ws, client)
yield self.close_future