Дразнить класс, но не одну из его функций - PullRequest
0 голосов
/ 23 мая 2018

Когда я импортирую MyApp из app.py, экземпляр класса SerialConnection создается немедленно.Я хочу издеваться над классом SerialConnection, но мне все еще нужна функция из этого класса SerialConnection.

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' 
...