根据不同的输入参数模拟 Python 函数 unittest python

Mocking Python function according to different input arguments unittest python

我有一个效用函数,它接受参数 case 和 return 相应的值

helper.py
def get_sport_associated_value(dictionary, category, case):
    if case == 'type':
        return "soccer"
    else: 
        return 1 #if case = 'id'

我有一个使用上述功能的主要功能

crud_operations.py
def get_data(category):
    dictionary ={.....}
    id =  get_sport_associated_value(dictionary, category, 'id')
    .....
    .....
    type = get_sport_associated_value(dictionary, category, 'type')
    ....
    return "successful"

现在我正在使用 unittest.Mock 对 get_data() 模块进行单元测试。我无法将值传递给 id 和类型 .

@mock.patch('helper.get_sport_associated_value')
def test_get_data(self, mock_sport):
    with app.app_context():
        mock_sport.side_effect = self.side_effect
        mock_sport.get_sport_associated_value("id")
        mock_sport.get_sport_associated_value("type")
        result = get_queries("Soccer")
        asserEquals(result, "successful")

 def side_effect(*args, **kwargs):
     if args[0] == "type":
         print("Soccer")
         return "Soccer"
     elif args[0] == "id":
         print("1")
         return 1

我尝试 this 使用 side_effect 函数 并面临模拟 get_sport_associated_value()[=35 的问题=]根据输入参数的不同取值。

问题 2:在这种情况下,使用 mockmock.magicmock 的最佳方法是什么?

感谢您对单元测试的任何帮助 谢谢

您错误地将 args[0] 测试为 caseside_effect 回调函数的参数应该与你想要模拟的函数相同:

def side_effect(dictionary, category, case):
    if case == "type":
        return "Soccer"
    elif case == "id":
        return 1