使用Autobahn WebSocket进行单元测试

4 投票
1 回答
2155 浏览
提问于 2025-04-17 15:08

我正在为我的应用程序编写单元测试,这个应用程序使用了Autobahn。

我想测试我的控制器,这些控制器会接收来自协议的数据,解析这些数据并做出反应。

但是,当我的测试到达一个应该断开连接的地方(self.sendClose)时,就会出现错误。

exceptions.AttributeError: 'MyProtocol' object has no attribute 'state'.

我尝试使用proto_helpers.StringTransportmakeConnection,但也出现了错误。

exceptions.AttributeError: StringTransport instance has no attribute 'setTcpNoDelay'`

我正在使用trial,而且我不想为了测试而运行一个虚假的服务器/客户端,因为这样做不太推荐。

我应该如何编写我的测试,以便能够测试发送数据、读取数据、断开连接等功能,使用假连接和trial呢?

1 个回答

5

要准确了解发生了什么,得先看看 MyProtocol 类。听起来问题很可能是因为你直接在操作一些底层函数,这样也就影响了 WebSocket 类的 state 属性,而这个属性其实是用来表示 WebSocket 连接的内部状态的。

根据 autobahn 的参考文档,你可以直接使用和重写的 WebSocketProtocol 的 API 有:

  • onOpen
  • onMessage
  • onClose
  • sendMessage
  • sendClose

你用 StringTransport 来测试你的协议的方法并不是最理想的。问题在于 MyProtocol 其实是建立在 autobahn 提供的 WebSocketProtocol 框架之上的一层小封装,这个框架隐藏了关于连接管理、传输和内部协议状态的细节,无论好坏。

想想看,你是想测试你自己的东西,而不是 WebSocketProtocol。所以如果你不想嵌入一个虚拟的服务器或客户端,最好的办法就是直接测试 MyProtocol 重写的方法。

我说的一个例子是:

class MyPublisher(object):
    cbk=None

    def publish(self, msg):
        if self.cbk:
            self.cbk(msg)

class MyProtocol(WebSocketServerProtocol):

    def __init__(self, publisher):
        WebSocketServerProtocol.__init__(self)
        #Defining callback for publisher
        publisher.cbk = self.sendMessage

    def onMessage(self, msg, binary)
        #Stupid echo
        self.sendMessage(msg)

class NotificationTest(unittest.TestCase):    

    class MyProtocolFactory(WebSocketServerFactory):
        def __init__(self, publisher):
            WebSocketServerFactory.__init__(self, "ws://127.0.0.1:8081")
            self.publisher = publisher
            self.openHandshakeTimeout = None

        def buildProtocol(self, addr):
            protocol =  MyProtocol(self.listener)
            protocol.factory = self
            protocol.websocket_version = 13 #Hybi version 13 is supported by pretty much everyone (apart from IE <8 and android browsers)
            return protocol

    def setUp(self):
        publisher = task.LoopingCall(self.send_stuff, "Hi there")        
        factory = NotificationTest.MyProtocolFactory(listener)
        protocol = factory.buildProtocol(None)
        transport = proto_helpers.StringTransport()
        def play_dumb(*args): pass
        setattr(transport, "setTcpNoDelay", play_dumb)
        protocol.makeConnection(transport)
        self.protocol, self.transport, self.publisher, self.fingerprint_handler =  protocol, transport, publisher, fingerprint_handler

    def test_onMessage(self):
        #Following 2 lines are the problematic part. Here you are manipulating explicitly a hidden state which your implementation should not be concerned with!
        self.protocol.state = WebSocketProtocol.STATE_OPEN
        self.protocol.websocket_version = 13
        self.protocol.onMessage("Whatever")
        self.assertEqual(self.transport.value()[2:], 'Whatever')

    def test_push(self):              
        #Following 2 lines are the problematic part. Here you are manipulating explicitly a hidden state which your implementation should not be concerned with!
        self.protocol.state = WebSocketProtocol.STATE_OPEN
        self.protocol.websocket_version = 13
        self.publisher.publish("Hi there")
        self.assertEqual(self.transport.value()[2:], 'Hi There')

正如你可能注意到的,使用 StringTransport 在这里非常麻烦。你必须了解底层框架,并绕过它的状态管理,这其实并不是你想要的。遗憾的是,autobahn 并没有提供一个现成的测试对象来方便地操作状态,因此我建议使用虚拟服务器和客户端的方法依然有效。


通过网络测试你的服务器

提供的测试展示了如何测试服务器推送,确保你收到的内容是你所期望的,同时也使用了一个钩子来判断何时结束测试。

服务器协议

from twisted.trial.unittest import TestCase as TrialTest
from autobahn.websocket import WebSocketServerProtocol, WebSocketServerFactory, WebSocketClientProtocol, WebSocketClientFactory, connectWS, listenWS
from twisted.internet.defer import Deferred
from twisted.internet import task 

START="START"            

class TestServerProtocol(WebSocketServerProtocol):

    def __init__(self):
        #The publisher task simulates an event that triggers a message push
        self.publisher = task.LoopingCall(self.send_stuff, "Hi there")

    def send_stuff(self, msg):
        #this method sends a message to the client
        self.sendMessage(msg)

    def _on_start(self):
        #here we trigger the task to execute every second
        self.publisher.start(1.0)

    def onMessage(self, message, binary):
        #According to this stupid protocol, the server starts sending stuff when the client sends a "START" message
        #You can plug other commands in here
        {
           START : self._on_start
           #Put other keys here
        }[message]()

    def onClose(self, wasClean, code, reason):
        #After closing the connection, we tell the task to stop sending messages
        self.publisher.stop()

客户端协议和工厂

接下来的类是客户端协议。它基本上是告诉服务器开始推送消息。它会调用 close_condition 来判断是否该关闭连接,最后,它会对收到的消息调用 assertion 函数,以检查测试是否成功。

class TestClientProtocol(WebSocketClientProtocol):
    def __init__(self, assertion, close_condition, timeout, *args, **kwargs):
        self.assertion = assertion
        self.close_condition = close_condition
        self._received_msgs = [] 
        from twisted.internet import reactor
        #This is a way to set a timeout for your test 
        #in case you never meet the conditions dictated by close_condition
        self.damocle_sword = reactor.callLater(timeout, self.sendClose)

    def onOpen(self):
        #After the connection has been established, 
        #you can tell the server to send its stuff
        self.sendMessage(START)

    def onMessage(self, msg, binary):
        #Here you get the messages pushed from the server
        self._received_msgs.append(msg)
        #If it is time to close the connection
        if self.close_condition(msg):
            self.damocle_sword.cancel()
            self.sendClose()

    def onClose(self, wasClean, code, reason):
        #Now it is the right time to check our test assertions
        self.assertion.callback(self._received_msgs)

class TestClientProtocolFactory(WebSocketClientFactory):
    def __init__(self, assertion, close_condition, timeout, **kwargs):
        WebSocketClientFactory.__init__(self, **kwargs)
        self.assertion = assertion
        self.close_condition = close_condition
        self.timeout = timeout
        #This parameter needs to be forced to None to not leave the reactor dirty
        self.openHandshakeTimeout = None

    def buildProtocol(self, addr):
        protocol = TestClientProtocol(self.assertion, self.close_condition, self.timeout)
        protocol.factory = self
        return protocol

基于试验的测试

class WebSocketTest(TrialTest):

    def setUp(self):
        port = 8088
        factory = WebSocketServerFactory("ws://localhost:{}".format(port))
        factory.protocol = TestServerProtocol
        self.listening_port = listenWS(factory)
        self.factory, self.port = factory, port

    def tearDown(self):
        #cleaning up stuff otherwise the reactor complains
        self.listening_port.stopListening()

    def test_message_reception(self): 
        #This is the test assertion, we are testing that the messages received were 3
        def assertion(msgs):
            self.assertEquals(len(msgs), 3)

        #This class says when the connection with the server should be finalized. 
        #In this case the condition to close the connectionis for the client to get 3 messages
        class CommunicationHandler(object):
            msg_count = 0

            def close_condition(self, msg):
                self.msg_count += 1
                return self.msg_count == 3

        d = Deferred()
        d.addCallback(assertion)
        #Here we create the client...
        client_factory = TestClientProtocolFactory(d, CommunicationHandler().close_condition, 5, url="ws://localhost:{}".format(self.port))
        #...and we connect it to the server
        connectWS(client_factory)
        #returning the assertion as a deferred purely for demonstration
        return d

这显然只是一个例子,但正如你所看到的,我并没有需要直接操作 makeConnection 或任何 transport

撰写回答