模拟一个类,但不是它的一个功能

时间:2018-05-22 21:22:51

标签: python unit-testing mocking patch

当我从app.py导入MyApp时,是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' 

0 个答案:

没有答案