当我从应用程序导入MyApp时。py,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'
我的家族。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'