簡體   English   中英

如何測試龍卷風read_message什么都沒讀

[英]How to test that tornado read_message got nothing to read

我正在進行龍卷風聊天,並且正在做一些測試,大多數客戶端消息都會從服務器生成回復,但是其他的則不能生成任何回復。

我設法用這段代碼做到了,等待讀取超時發生,還有更好的方法嗎?

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來自外部的@gen_test

只是為了說明@Ben Darnell的答案

from tornado import gen

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(gen.TimeoutError):
            response = yield gen.with_timeout(datetime.timedelta(seconds=4), ws.read_message()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM