龙卷风测试异步请求

时间:2013-04-26 03:45:35

标签: python unit-testing tornado

我需要一个关于测试龙卷风应用的建议。现在我只是玩演示聊天应用程序,但它看起来像现实生活中的问题。

在处理程序中我有:

class MessageUpdatesHandler(BaseHandler):
    @tornado.web.authenticated
    @tornado.web.asynchronous
    def post(self):
        cursor = self.get_argument("cursor", None)
        global_message_buffer.wait_for_messages(self.on_new_messages,
                                                cursor=cursor)

    def on_new_messages(self, messages):
        # Closed client connection
        if self.request.connection.stream.closed():
            return
        self.finish(dict(messages=messages))


class MessageBuffer(object):
    def __init__(self):
        ....

    def wait_for_messages(self, callback, cursor=None):
        if cursor:
            new_count = 0
           for msg in reversed(self.cache):
                if msg["id"] == cursor:
                    break
                new_count += 1
            if new_count:
                callback(self.cache[-new_count:])
                return
        self.waiters.add(callback)

    def cancel_wait(self, callback):
        .....

    def new_messages(self, messages):
        logging.info("Sending new message to %r listeners", len(self.waiters))
        for callback in self.waiters:
            try:
                callback(messages)
            except:
                logging.error("Error in waiter callback", exc_info=True)
        self.waiters = set()
        self.cache.extend(messages)
        if len(self.cache) > self.cache_size:
            self.cache = self.cache[-self.cache_size:]

正如我所提到的,完整源代码位于torndado demos

在我的测试中,我有:

@wsgi_safe
class MessageUpdatesHandlerTest(LoginedUserHanldersTest):
    Handler = MessageUpdatesHandler

    def test_add_message(self):
        from chatdemo import global_message_buffer
        kwargs = dict(
            method="POST",
            body='',
        )
        future = self.http_client.fetch(self.get_url('/'), callback=self.stop, **kwargs)
        message = {
        "id": '123',
        "from": "first_name",
        "body": "hello",
        "html": "html"
        }
        global_message_buffer.new_messages([message])
        response = self.wait()
        self.assertEqual(response.code, 200)
        self.mox.VerifyAll()

会发生什么:

  1. 创建未来对象
  2. 发送一条问候消息,此时没有注册waiterMessageBuffer中,因此不会调用回调
  3. wait启动IoLoop并制作,提取后,waiter成为 在MessageBuffer
  4. 注册
  5. 永远不会调用回调,我的回复仍为空 一切都失败了

    AssertionError:异步操作超时     5秒后

  6. 我想要它做什么:

    1. 在邮寄注册本身作为服务员
    2. 收到一些消息
    3. 给我回复200条
    4. 感谢您的帮助

0 个答案:

没有答案