gpt4 book ai didi

python - 如何测试 Tornado read_message 没有什么可读的

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:02 26 4
gpt4 key购买 nike

我有一个 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()

测试结束时也有问题

======================================================================
ERROR: test_no_reply (myproj.tests.ChatTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 120, in __call__
result = self.orig_method(*args, **kwargs)
File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 506, in post_coroutine
self._test_generator.throw(e)
StopIteration

最佳答案

一般来说,很难测试出阴性结果:您要等多久才能得出您正在测试的事情永远不会发生的结论?最好重新安排事情,以便测试能够以积极的方式表达。在这个玩具示例中这很难做到,但请考虑以下处理程序:

class RealtimeHandler(tornado.websocket.WebSocketHandler):
def on_message(self, message):
if int(message) % 2 == 1:
self.write_message('%s is odd' % message)

在这种情况下,您可以通过发送消息 1、2 和 3 来测试它,并断言您收到两个响应:“1 是奇数”和“3 是奇数”。

您看到的 StopIteration 失败让我有点惊讶:我不希望在 @gen_test 方法中捕获超时,因此这样做可能会产生意想不到的结果,但我没想到它会变成 StopIteration。无论如何,最好重新构建测试,这样您就不必依赖超时。如果您确实需要超时,请使用 gen.with_timeout,这样您就可以从测试内部控制超时,而不是依赖 @gen_test 外部的超时。

关于python - 如何测试 Tornado read_message 没有什么可读的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com