I am trying to mock a variable that represents the a state of a device
In this case I have am trying to add a device and I have the following code:
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" )
What am I am doing is mocking the self.network.controller.add_node( secure ) and when I do that I change the self.commandState to Starting.... What I wanted to accomplish is after about 5 seconds change it to self.COMMAND_COMPLETED in order to finish the operation successfully.
Any ideias how to mock this?
Since your code is blocking (programme flow stays on that loop until it is finished), an option without messing too much with your current code is to span a thread that changes the variable after a given time.
Let's assume that your code is inside a method called
run_loop
, and within a classMyClass
. Given a simple test code like this:You could change it to something like the following. I have not tested it, and can be refined a lot, but you get the idea: