gpt4 book ai didi

python - 返回作为参数传递的相同值的模拟方法

转载 作者:行者123 更新时间:2023-11-28 22:20:28 25 4
gpt4 key购买 nike

我如何使用 python unittest.mock 模拟 python 方法,它将返回作为参数传递的相同值,

我试过了,

from unittest.mock import MagicMock

def dummy_function(value):
"Will return same value as value passed to the function"
return value

# To moke gettext function used in template
# Then I pass this mock method to Jinja2 template to moke gettext string
_ = MagicMock(return_value=dummy_function)

当我打印 jinja 模板时,它会显示类似下面的测试,

<div class="order_details">\n                
<legend class="badge">&lt;function dummy_function at 0x10887f730&gt;</legend>\n
</div>\n

原始Jinja2模板有

<div class="order_details">             
<legend class="badge">_('Details')</legend>
</div>

最佳答案

return_value 只是一个要返回的固定对象,您只是告诉模拟调用的结果是一个函数对象。

您想使用 side_effect attribute相反:

_ = MagicMock(side_effect=dummy_function)

side_effect 设置为一个函数会导致它被调用时使用与 mock 相同的参数。查看documentation :

If you pass in a function it will be called with same arguments as the mock and unless the function returns the DEFAULT singleton the call to the mock will then return whatever the function returns.

演示:

>>> from unittest.mock import MagicMock
>>> identity = lambda a: a
>>> MagicMock(return_value=identity)('called') # returns the function object, it won't call it
<function <lambda> at 0x10fa61620>
>>> MagicMock(side_effect=identity)('called') # will call the function
'called'

关于python - 返回作为参数传递的相同值的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com