1

I'm in the means of doing a Python embedded project where I'm using Python-OpenZwave to communicate with a sensor via a z-wave dongle. And I need to do some unit testing on functions I have implemented. I'm not that experienced in unit testing, and have run into a problem with dependencies that I need to get rid of during the unit testing, because some of these funtions I have implemented communicates with the sensor and therefore only work on my embedded platform.

One of the functions I need to test is shown below, it takes 2 arguments, first is the ID of the sensor, the second is a network class object from the OpenZWave libary. It first sets the ID of the sensor we are working with in the class through a function call, second gets all data from the sensor and saves it as a dict in the class object, whereafter I search through all the data for the temperature value and return it;

def get_temperature(sensor_id, network_obj):
    multisensor = network_obj.nodes[sensor_id]
    multisensor.get_values()
    values = {}
    for value in multisensor.values:
        if multisensor.values[value].label == 'Temperature':
            values = {'Temperature': multisensor.values[value].data}
    return values

The thing I need help with, is how I can get rid of the dependency coming from the class object which is parsed to the function? I have tried methods I found online Patching, MonkeyPatching, Mock and MagicMock but haven't been able to make any of it work. So I would like some advice on how I can get rid of the dependencies and what libary / tool I should use in this case.

Thanks in advance

Gubimand
  • 11
  • 1
  • I suggest to write a fake `network_obj` class of your own, that mimics the real class but gives pre-defined temperature readings. Then you call the real function injecting your fake class and test the results against the pre-defined. – progmatico Nov 09 '20 at 22:22
  • It should be possible to mock the class with unittest.mock.Mock objects and then check the calls made, but it looks to me it would be more complicated than the pre-fab fake. – progmatico Nov 09 '20 at 22:26
  • @progmatico thanks for your respons! Yea I can see your point, in that it would be easiere to make my own fake class and call the function with the fake object instead of doing trial and error with Mock. And with the time constraint I have with the project that would probably be the smartest to do, So I will do that, thank you! – Gubimand Nov 10 '20 at 11:22

0 Answers0