我正在尝试编写一些测试用例,通过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从未接触到这个新创建的协议。我的问题是,有没有办法在客户端连接后通过我的代码获取新创建的实例?
答案 0 :(得分:0)
I found a stupid way around this by using garbage collector to retrieve the instance like so
#Used to get the instance of the protocol
def getIn(self):
for obj in gc.get_objects():
if isinstance(obj, SlowSquareClientProtocol):
protocol = obj
return protocol
def test_00_startSession(self):
WSJsonFormatter = WSformat()
x = WSJsonFormatter.formatCreateSession("eng-USA", sessionId = "837ab900-912e-11e6-b83e-3f30a2b99389")
SlowSquareClientProtocol.sendMessage(self.getIn(),json.dumps(x).encode('utf8'))
print("Request {} sent.".format(x))
So i searched all instances which have the name of the class I am looking for, and then pass it in the sendmessage method. I am still opened to other simpler suggestions :)