Python如何模拟多个类方法

2024-06-16 09:36:04 发布

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

我正在一个子类中编写一个新方法。该方法将json对象发布到MQTT代理上,并对来自客户机的响应进行计时。 为了对它进行单元测试,我想修补发布json消息的方法(由被测试的方法调用)并为响应计时。 如果没有模拟的能力,则依赖于现有的MQTT代理和发布响应的客户机。另一个原因是内省被测试方法传递给mock方法的参数(json对象)。 到目前为止,我已经能够修补类'init方法,因为它初始化了许多我不需要的东西来测试我的方法(记录器、配置文件等)。但是,当我尝试修补同一类上的另一个方法时。被测试的方法调用真正的publish方法,而不是mock方法。 我使用的是Python2.7(不是自己选择的)。 我使用behave作为单元测试框架。你知道吗

我有一个要单元测试的特性,它依赖于每个场景运行的类似上下文。因此,在环境.py(类似于pytest的康菲公司),我将实例化一次类,以便在整个特性中运行。这个很好用。当我向“publish\u json”方法添加另一个补丁时。它调用实方法并失败,因为没有运行MQTT代理。你知道吗

我还尝试在teststep实现文件中使用MagicMock模拟“publish\ujson”方法。但是,它返回了一个不包含参数的call()对象。你知道吗

类的结构。你知道吗

BaseClass
    __init__ which i've successfully patched.
    contains the publish_json which i'm unable to patch.

    aSubClass(BaseClass)
        containing derived functionality 

        anotherSubClass(aSubClass)
            containing the new method to test.
            will eventually use the functionality within the parent classes.
# environment.py...
from anotherSubClass import anotherSubClass

def fake_pub():
        print("the fake json publisher has been called!!!")
        return True

@fixture
def anotherSubClass_mocked(context):
        # pacthing out the base class initialisation
        # patching the publish_json method which isn't working
        with patch.object(anotherSubClass, "__init__", lambda x,y,z: None), patch.object(anotherSubClass, "publish_json", fake_pub):
                context.tester = anotherSubClass(None,None)

# steps.py
@when(u'the tester sends a START message')
def step_impl(context):
    # patch the publish_json call here and validate the json contents (call_args)
    context.tester.publish_json = Mock()
    context.tester.time_mqtt_msg("START")
    args = context.tester.publish_json.call_args()

# method under test
from aSubClass import aSubClass


class anotherSubClass(aSubClass):

    def time_cloud_msg(self, msg, timeout=10):
      mqtt_msg = {"msg":"TEST", "time": self.generate_timestamp()}
      print("Sending message to remote broker")
      self.publish_json("remote", "command", mqtt_msg)
      # timer not yet implemented... :-(

期望调用假json发布者。 在第一个实例中(在环境中)调用了实际的publish方法 在第二个实例中(在步骤中),mock应该是在没有任何内容的情况下调用的(call())


Tags: the对象方法json代理defcontextmsg