0

I am trying to unit test a python module that interacts with an object which is initialized with a serial port. At the moment the test passes just if there is something connected to that serial port on the host computer.

class TestParse(unittest.TestCase):
    cmd_mock = mock.Mock()   # for mocking '_cmd' method in 'vp'
    loop_mock = mock.Mock()  # for mocking '_loop_cmd' method in 'vp'

    def test_unpack_loop_data(self):
        LoopStruct.unpack(codecs.decode(loop_data, 'hex'))

    @mock.patch.object(VantagePro, '_cmd', cmd_mock)
    @mock.patch.object(VantagePro, '_loop_cmd', loop_mock)
    def test_fields(self):
        self.loop_mock.return_value = codecs.decode(loop_data, 'hex')

        # this is working just if there is an actual device attached.
        vp = VantagePro('/dev/ttyUSB0')
        fields = vp._get_loop_fields()

        ..... do something to test ..........

The object is VantagePro. How can I mock its initialization?

Saverio Guzzo
  • 419
  • 5
  • 16
  • Replace the entire object with a mock? – AKX Feb 04 '22 at 09:15
  • I did something like this: `with mock.patch.object(VantagePro('/dev/ttyUSB0'), 'port') as vp: fields = vp._get_loop_fields()` However, my `fields` dictionary just contain a MagicMock object now.. – Saverio Guzzo Feb 04 '22 at 09:41
  • 1
    Hi, why don't you mock `_get_loop_fields` method to return the expected dictionary? – Laurent Feb 06 '22 at 09:08

0 Answers0