模拟一个类,但不模拟它的一个函数

2024-09-20 22:52:17 发布

您现在位置:Python中文网/ 问答频道 /正文

当我从app.py导入MyApp时,SerialConnection类的一个实例 立即创建。我想模拟SerialConnection类,但仍然需要该SerialConnection类中的函数

应用程序.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

测试应用程序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' 

Tags: thetofrompyimportselfdefdecorator

热门问题