【问题标题】:How to get instance of a class in python如何在python中获取类的实例
【发布时间】: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


    【解决方案1】:

    我发现了一个愚蠢的方法,通过使用垃圾收集器来检索实例,就像这样

    #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))
    

    所以我搜索了所有具有我要查找的类名称的实例,然后将其传递给 sendmessage 方法。我仍然愿意接受其他更简单的建议:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 2021-10-14
      相关资源
      最近更新 更多