首页 > 解决方案 > 根据不同的输入参数模拟Python函数unittest python

问题描述

我有一个实用函数,它接受参数大小写并相应地返回值

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 和 type

@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

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

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

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

标签: pythonunit-testingmockingmagicmock

解决方案


您错误地测试args[0]case. 回调函数的参数side_effect应该与您要模拟的函数相同:

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

推荐阅读