简体   繁体   English

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

[英]Mock function to return different value based on argument passed

In my test function, my mocks are not behaving properly because when I mock my get_config function, I only know how to mock it to return one value.在我的测试函数中,我的模拟行为不正常,因为当我mock我的get_config函数时,我只知道如何模拟它以返回一个值。 How can I add some logic to my mock in order for the mock to return a different value only when get_config is passed the argument of "restricted"如何在我的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()

You can assign a function to side_effect as described in official doc您可以按照官方文档中的说明将函数分配给side_effect

from unittest.mock import Mock

def side_effect(value):
    return value

m = Mock(side_effect=side_effect)
m('restricted')
'restricted'
class Ctx():
  def get_config(confName):
    return confName

def mock_get_config(value):
  if value == "conf1":
    return "confA"
  elif value == "conf2":
    return "confB"
  else:
    return "UnknownValue"

class CtxSourceFileTrial(unittest.TestCase):
  def test(self):
    mockCtx = Mock()
    mockCtx.get_config.side_effect = mock_get_config
    self.assertEqual("confA", mockCtx.get_config("conf1"))
    self.assertEqual("confB", mockCtx.get_config("conf2"))

#
# By the way I think Python is EXTREMELY screwy, Adligo
#

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

相关问题 获取传递给 mock_open 的参数并为模拟调用不同的函数 - Get the argument passed to mock_open and call a different function for mock python 用不同的参数模拟 function 并用返回值断言 - python mock a function with different argument and assert with return values 如何根据模拟的函数使用Python Mock副作用返回不同的值 - How to user Python Mock side effect to return different value based on function being mocked 在python函数中模拟具有不同返回值的相同方法两次 - Mock same method with different return value called twice in a function in python 模拟方法返回与参数相同的值 - Mock method which returns same value passed as argument Python Typing:根据函数参数声明返回值类型 - Python Typing: declare return value type based on function argument 如何从通过另一个 function (带参数)作为参数的 function 返回一个值? 我得到一个类型错误 - How to return a value from a function which was passed another function (with arguments) as an argument? I get a TypeError 模拟测试动态函数的返回值 - mock testing the return value of a dynamic function 如何模拟类函数的返回值 - How to mock the return value of a class's function 根据传递给外部函数的参数调用内部函数 - Call inner function based on the argument passed to outer function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM