簡體   English   中英

使用Web套接字進行龍卷風單元測試 - 堆棧上下文怎么樣?

[英]Tornado unit test with web sockets - what about stack context?

我一直在使用龍卷風服務器,我不得不說我喜歡它。 我有一個龍卷風服務器(運行在python3.2上),處理Web套接字和http請求。 我想要做的是寫一些單元測試(使用web套接字)和ws2py(它實現了一個與龍卷風IOLoop一起使用的ws客戶端)。 我看到tornado有AsyncTestCase類,它看起來很有趣,特別是當它與AsyncHTTPClient一起使用時,如其文檔中所述

class MyTestCase2(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        client.fetch("http://www.tornadoweb.org/", self.stop)
        response = self.wait()
        # Test contents of response
        self.assertIn("FriendFeed", response.body)

我想將AsyncTestCase與Web套接字一起使用,客戶端不是問題,我可以毫無問題地發送和接收消息。

我想我要做的是將self.stop作為回調傳遞給客戶端,以便通過調用wait()來檢索收到的消息,如上例所示。 但不知怎的,這不起作用,這就是我所擁有的:

class SQLRequests(AsyncTestCase):
    """Tests sql requests"""

    def test_sql_req_1(self):
        """first test function"""
        client = AsyncWSClient(httpBaseUrl, self.io_loop)
        client.sendMessage('some_message', self.stop)

        response = self.wait()
        if response.data:
            print('got %s' % str(response.data))
            # some test
            self.assertTrue(True)


if __name__ == '__main__':
    unittest.main()

這是我的Web套接字客戶端:

class AsyncWSClient(TornadoWebSocketClient):
"""
Asynchronous web socket client based on ws4py's tornadoclient
Sends a message and calls callback with received message
"""
def __init__(self, url, ioLoop=None, **kwargs):
    TornadoWebSocketClient.__init__(self, url, io_loop=ioLoop, **kwargs)
    self._callback = None
    self._message = None

def opened(self):
    """called when web socket opened"""
    self.send(self._message, binary=False)      

def received_message(self, message):
    """Received a message"""
            self.close()
    if self._callback:
        self._callback(message)

def sendMessage(self, message, callback):
    """Connects and sends message when connected"""
    self._message = message
    self._callback = callback
    self.connect()

我確實收到一個ws2py.messaging.TextMessage對象作為響應,但它的數據字段為None盡管客戶端已收到一些數據。 如果我查看AsyncTestCase,在它調用回調之前,該對象中有一些數據,當它作為wait()的返回值傳遞時會以某種方式消失。

我看到龍卷風中有一個神秘的東西叫做stack_context,有什么與我的問題有關嗎?

問題是消息“data”包含在messagedata屬性中。 調用received_messagemessage.data將重置為None( https://github.com/Lawouach/WebSocket-for-Python/blob/master/ws4py/websocket.py#L369 )。

所以,只需調用你的回調傳遞message.data而不是完整的message 像那樣:

def received_message(self, message):
    """Received a message"""
    self.close()
    if self._callback:
       self._callback(message.data)

暫無
暫無

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

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