我有一个Tornado聊天,我正在做一些测试,大多数客户机消息都会从服务器生成一个回复,但是其他的不能生成任何回复。在
我用这段代码设法做到了,等待读超时发生,有没有更好的方法来做呢?在
import json
import tornado
from tornado.httpclient import HTTPRequest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
class RealtimeHandler(tornado.websocket.WebSocketHandler):
def on_message(self, message):
if message != 'Hi':
self.write_message('Hi there')
return
class ChatTestCase(AsyncHTTPTestCase):
def get_app(self):
return Application([
('/rt', RealtimeHandler),
])
@gen_test
def test_no_reply(self):
request = HTTPRequest('ws://127.0.0.1:%d/rt' % self.get_http_port())
ws = yield websocket_connect(request)
ws.write_message('Hi')
with self.assertRaises(tornado.ioloop.TimeoutError):
response = yield ws.read_message()
测试结束时也有一个问题
^{pr2}$
一般来说,测试一个阴性是很困难的:你要等多久才能断定你要测试的东西永远不会发生?最好把事情重新安排一下,这样测试就可以用积极的语言来表达。在这个玩具示例中很难做到这一点,但请考虑以下处理程序:
在本例中,您可以通过发送消息1、2和3来测试它,并断言您得到两个响应,“1是奇数”和“3是奇数”。在
您看到的
StopIteration
失败让我有点吃惊:我不希望在@gen_test
方法中捕捉到超时,因此这样做可能会产生意外的结果,但我没有料到它会变成StopIteration
。无论如何,最好重新构造测试,这样就不必依赖超时。如果您确实需要超时,请使用gen.with_timeout
,这样您就可以从测试内部控制超时,而不是依赖来自外部到内部的超时。在只是为了说明@Ben Darnellanswer。在
相关问题 更多 >
编程相关推荐