【发布时间】:2016-10-19 15:06:23
【问题描述】:
我正在尝试编写一些测试用例,通过 websockets 创建客户端来评估服务器的响应。我正在使用高速公路建立连接。但是,我似乎无法向服务器发送消息,因为我需要协议类的当前活动实例才能运行 sendMessage。代码如下:
class SlowSquareClientProtocol(WebSocketClientProtocol):
def onOpen(self):
print "Connection established"
def onMessage(self, payload, isBinary):
if not isBinary:
res = json.loads(payload.decode('utf8'))
print("Result received: {}".format(res))
self.sendClose()
def onClose(self, wasClean, code, reason):
if reason:
print(reason)
reactor.stop()
class NLVRTR(TestFixture,SlowSquareClientProtocol):
@classmethod
def setUpClass(self):
log.startLogging(sys.stdout)
factory = WebSocketClientFactory(u"ws://someURL:8078")
factory.protocol = SlowSquareClientProtocol
reactor.connectTCP("someURL", 8078, factory)
wsThread = threading.Thread(target = reactor.run,
kwargs={'installSignalHandlers':0})
wsThread.start()
def test_00_simple(self):
WSJsonFormatter = WSformat()
x = WSJsonFormatter.formatGetInfo(2)
self.sendMessage(json.dumps(x).encode('utf8'))
print("Request to square {} sent.".format(x))
所以为了详细说明,我在 setUpClass 方法中启动了客户端,并尝试在 test_00_simple 中发送一些消息。但是,我似乎遇到了这样的错误
AttributeError: 'NLVRTR' object has no attribute 'state'
State 应该是 WebSocketClientProtoco 内部定义的属性。如果我将 sendmessage 放在 onOpen 方法中,一切正常,但是除了在 SlowSquareClientProtocol 类中之外,我不能从其他任何地方调用它。在高速公路的文档中,提到了
Whenever a new client connects to the server, a new protocol instance will be created
我相信这就是问题所在,它创建了一个新的协议实例,而 sendmessage 方法正在使用该实例。由于我没有在 slowsquare... 类中调用它,因此当客户端连接时,sendmessage 从未捕获到这个新创建的协议,因此出现错误。我的问题是,一旦客户端连接,我有什么方法可以通过我的代码获取新创建的实例?
【问题讨论】:
标签: python python-2.7 unit-testing websocket autobahn