在python中模拟变量

时间:2016-02-10 10:44:56

标签: python magicmock

我正在尝试模拟一个代表设备状态的变量

在这种情况下,我正在尝试添加设备,我有以下代码:

if self.network.controller.add_node( secure ) :
    for i in range( 0, 60 ) :
        if flagStarted :
            if self.commandState == self.COMMAND_FAILED or self.commandState == self.COMMAND_FAILED :
            # Transaction Failed or Error
            self.network.controller.cancel_command( )
            self.log.warning( " *** Add Device Failed *** " )
            return False
        elif self.commandState == self.COMMAND_CANCEL :
            # Transaction Canceled
            self.log.debug( " *** Command Canceled " )
            return False
        elif self.commandState == self.COMMAND_COMPLETED :
            # Transaction Completed
            value = ZWaveProtocol.getAddedDevice( )
            if value > 0 :
                dev = DeviceCollection.getDeviceByProtocolID( value, "ZWave" )
                return dev.id
            else :
                if self.commandState == self.COMMAND_STARTING or self.commandState == self.COMMAND_WAITING :
                flagStarted = True
        sys.stdout.write( "." )
        sys.stdout.flush( )
        time.sleep( 1.0 )

    self.network.controller.cancel_command( )
    return -1
else :
    self.log.error( "Failed to add device" )

我正在做的是嘲笑self.network.controller.add_node(安全),当我这样做时,我将self.commandState更改为Starting ....我想要完成的是在大约5秒后更改它to self.COMMAND_COMPLETED以便成功完成操作。

任何想法如何模仿这个?

1 个答案:

答案 0 :(得分:1)

由于你的代码是阻塞的(程序流一直停留在该循环上),所以在没有过多使用当前代码的情况下选择是跨越在给定时间后更改变量的线程。

假设您的代码位于名为run_loop的方法内,并且位于类MyClass内。给出一个简单的测试代码:

def test_1():
  obj = MyClass()
  # Mock something
  obj.run_loop()
  # Do your assertions

您可以将其更改为以下内容。我没有对它进行测试,并且可以进行很多改进,但是你明白了这个想法:

from threading import Thread
from time import sleep

def change_state(obj):
    sleep(5)
    obj.commandState = obj.COMMAND_COMPLETE

def test_1():
  obj = MyClass()

  # Launch a thread that within 5 seconds will change the state of `obj`
  Thread(target=change_state, args=[obj]).start()

  # Call the main loop, which will recognize that the state changed within 5 secs
  obj.run_loop()