Ste*_*uso 10 python unit-testing asynchronous tornado websocket
我正在开发一个与龙卷风的websocket功能兼容的项目.我看到有大量文档用于处理异步代码,但没有关于如何使用它来创建与其WebSocket实现一起使用的单元测试.
是否tornado.testing
提供了执行此操作的功能?如果是这样,有人可以提供一个如何实现它的简短示例吗?
提前致谢.
小智 15
正如@Vladimir所说,您仍然可以使用AsyncHTTPTestCase
创建/管理测试Web服务器实例,但您仍然可以像正常的HTTP请求一样测试WebSockets - 没有语法糖可以帮助您.
Tornado也有自己的WebSocket客户端,因此没有必要(据我所见)使用第三方客户端 - 也许这是最近添加的.所以尝试类似的东西:
import tornado
class TestWebSockets(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
# Required override for AsyncHTTPTestCase, sets up a dummy
# webserver for this test.
app = tornado.web.Application([
(r'/path/to/websocket', MyWebSocketHandler)
])
return app
@tornado.testing.gen_test
def test_websocket(self):
# self.get_http_port() gives us the port of the running test server.
ws_url = "ws://localhost:" + str(self.get_http_port()) + "/path/to/websocket"
# We need ws_url so we can feed it into our WebSocket client.
# ws_url will read (eg) "ws://localhost:56436/path/to/websocket
ws_client = yield tornado.websocket.websocket_connect(ws_url)
# Now we can run a test on the WebSocket.
ws_client.write_message("Hi, I'm sending a message to the server.")
response = yield ws_client.read_message()
self.assertEqual(response, "Hi client! This is a response from the server.")
# ...etc
Run Code Online (Sandbox Code Playgroud)
无论如何,希望这是一个很好的起点.
我尝试在tornado.websocket.WebSocketHandler
基于处理程序的基础上实现一些单元测试并得到以下结果:
首先肯定AsyncHTTPTestCase
缺乏网络套接字支持。
尽管如此,人们至少可以使用它来管理IOLoop
和应用重要的东西。不幸的是,tornado 没有提供 WebSocket 客户端,因此这里输入侧面开发的库。
以下是使用 Jef Balog 的龙卷风 websocket 客户端对 Web Socket 进行的单元测试。