Tornado 的 WebsocketClientConnection 的关闭方法不调用 Websocket 处理程序on_close方法



我有一个类似的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从未被调用!

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

我使用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

相关内容

  • 没有找到相关文章

最新更新