2016-02-10 125 views
0

我試圖嘲弄代表一個設備懲戒在python

在這種情況下,我都在嘗試添加設備的狀態變量的變量,我有以下代碼:

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到開始....我想做到的是後約5秒鐘將其更改爲什麼self.COMMAND_COMPLETED才能成功完成操作。

任何ideias如何嘲笑呢?

回答

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