简体   繁体   English

Python模拟延迟side_effect评估

[英]Python Mock Delay side_effect valuation

Is there any way to delay the evaluation of a Mock side_effect. 有什么方法可以延迟对Mock side_effect的评估。

def mockfunc(wheel):
    wheel.rubber = soft

wheel.make = Mock(side_effect=mockfunc(wheel)))

The problem here is that I'm trying to replace the 'wheel.make' method such that when it is called under test, mockfunc is instead called and one of the wheel attributes is set instead of running the usual method. 这里的问题是,我正在尝试替换'wheel.make'方法,以便在测试中调用它时,将改为调用模仿函数并且设置了wheel属性之一,而不是运行常规方法。

Thing is - when I set the side_effect, the mockfunc call happens immediately, The rubber attribute is set to soft. 事情是-当我设置side_effect时,mockfunc调用立即发生,rubber属性设置为soft。 I don't want this to happen until the method wheel.make is called. 我不希望在调用wheel.make方法之前发生这种情况。

According to side_effect documentation it should be a callable, an iterable or an exception (class or object). 根据side_effect文档,它应该是可调用,可迭代或异常(类或对象)。 Moreover I guess you want to replace a unboundmethod make in wheel 's Class: to do these kind of patching you should use patch or patch.object as context or decorator as described here . 而且我猜你要替换一个unboundmethod makewheel的类别:做这些类型的补丁,你应该使用的patchpatch.object被描述为上下文或装饰在这里

Follow is a complete example of how to do it: 以下是如何执行此操作的完整示例:

from mock import patch

class Wheel():
    def __init__(self):
        self.rubber = 0

    def make(self):
        self.rubber = 10

soft = 36
def mockfunc(wheel):
    wheel.rubber = soft

wheel = Wheel()
print("unpatched wheel before make rubber = {}".format(wheel.rubber))
wheel.make()
print("unpatched wheel after make rubber = {}".format(wheel.rubber))

with patch.object(Wheel, "make", side_effect=mockfunc, autospec=True):
    print("patched wheel before make rubber = {}".format(wheel.rubber))
    wheel.make()
    print("patched wheel after make rubber = {}".format(wheel.rubber))

And the output is 输出是

unpatched wheel before make rubber = 0
unpatched wheel after make rubber = 10
patched wheel before make rubber = 10
patched wheel after make rubber = 36

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM