Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

python - Mocking when inheriting from pyserial

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...