gpt4 book ai didi

python - 模拟函数根据传递的参数返回不同的值

转载 作者:行者123 更新时间:2023-12-01 09:21:53 26 4
gpt4 key购买 nike

在我的测试函数中,我的模拟行为不正常,因为当我模拟我的get_config函数时,我只知道如何模拟它以返回一个值。如何向我的 mock 添加一些逻辑,以便仅当 get_config 传递 "restricted" 参数时模拟才返回不同的值>

def func():
conf1 = get_config("conf1")
conf2 = get_config("conf2")
conf3 = get_config("conf3")
restricted_datasets = get_config("restricted")
dataset = get_config("dataset")
if dataset not in restricted_datas:
return run_code()

最佳答案

您可以将函数分配给 side_effect,如 official doc 中所述。

from unittest.mock import Mock

def side_effect(value):
return value

m = Mock(side_effect=side_effect)
m('restricted')
'restricted'

关于python - 模拟函数根据传递的参数返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50748057/

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