Mocking a variable in python

432 Views Asked by At

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?

1

There are 1 best solutions below

0
bgusach On BEST ANSWER

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 class MyClass. Given a simple test code like this:

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

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:

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