I have a class that inherits from pyserial
's serial.Serial
class that looks something like this:
class SYM1(serial.Serial):
def __init__(self, *args, debug=None, baudrate=4800, timeout=1, **kwargs):
super().__init__(*args, baudrate=baudrate, timeout=timeout, **kwargs)
LOG.info('using port %s', self.port)
def read(self, count):
...
return super().read(count)
def write(self, data):
...
return super().write(data)
def connect(self):
...
def send_command(self, cmd, *args):
...
I would like to write unit tests for the class, but I'm unsure how best to set things up such that (a) methods defined on the SYM1
class are callable normally, while (b) methods inherited from serial.Serial
are mocked out.
I started with this:
import pytest
import serial
from unittest import mock
serial.Serial = mock.MagicMock
from symtool import symtool # NOQA
@pytest.fixture
def sym(monkeypatch):
s = symtool.SYM1('TESTDEV')
s.connect()
return s
def test_connect(sym):
pass
But that fails here:
LOG.info('using port %s', self.port)
With:
AttributeError: Mock object has no attribute 'port'
and that puzzles me, because if it's a mock.Mock
object, I would expect:
>>> from unittest import mock
>>> m = mock.Mock()
>>> m.port
<Mock name='mock.port' id='139910315631568'>
It's not just simple attributes; if I comment out the line causing the first AttributeError
, it will instead fail later on when calling super().write
:
AttributeError: 'super' object has no attribute 'write'
What's going on here, and what's the right way to do it?
question from:
https://stackoverflow.com/questions/66066693/mocking-when-inheriting-from-pyserial 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…