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

问题描述 投票:0回答:1

我有一个实用函数,接受参数case,并相应地返回值

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函数 this并面临根据输入参数的不同值模拟get_sport_associated_value()的问题。

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

任何帮助对单元测试表示赞赏谢谢

python unit-testing mocking magicmock
1个回答
0
投票
您将args[0]错误地测试为caseside_effect回调函数的参数应与您要模拟的函数相同:

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

© www.soinside.com 2019 - 2024. All rights reserved.