Mock a Class, but not one of its functions

2019-09-01 02:23发布

When I import MyApp from app.py, a instance of the SerialConnection class is created immediately. I want to mock the SerialConnection class but I still need a function from within this SerialConnection class.

app.py

# A module that creates strings that is sent via SerialConnection

from myserial import SerialConnection

class MyApp():

    global ser
    ser = SerialConnection()   # ---> Needs to be mocked

    def __init__(self):
        pass

    @ser.decorator             # ---> Needs to be by-passed
    def myfunc(self):
        return 'testing1234'

myserial.py

# A module to write and read to a serial/UART buffer

from functools import wraps
import serial

class SerialConnection():

        def __init__(self):
            """ Initilize the Serial instance. """

            self.ser = serial.Serial(port=2, baudrate=9600)

        def decorator(self, func):
            @wraps(func)
            def wrapper_func(*args):
                return func(*args)
            return wrapper_func

test_app.py

# This file tests the function "myfunc" from "MyApp" class.

from patch import mock

@patch('myserial.SerialConnection')
def test_myfunc(mock_class):

    # I can now import MyApp successfuly...
    from app import MyApp

    # ..but I need to bypass the decorator myserial.SerialConnection.decorator
    # do I add a by-pass decorator to the "mock_class"?

# myfunc() turns out to be mocked and not a real function
assert MyApp().myfunc() == 'testing1234' 

0条回答
登录 后发表回答