python - 根据不同的输入参数模拟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:在这种情况下使用mock或mock.magicmock的最佳方法是什么?
感谢单元测试的任何帮助谢谢
解决方案
您错误地测试args[0]
为case
. 回调函数的参数side_effect
应该与您要模拟的函数相同:
def side_effect(dictionary, category, case):
if case == "type":
return "Soccer"
elif case == "id":
return 1
推荐阅读
- android - SurfaceView - 捏缩放而不损失质量
- angular - 是否有设置 ngxDaterangepicker 的 endKey 的替代方法?
- javascript - 表单验证未识别空白输入
- sql - 在rails中加入没有关系的表
- embedded - 接收 CAN FD 报文的 CAPL 程序(64 字节)
- windows - 列表显示; 没有 RTL 布局的工具提示
- python - 如何从 python 库签署谷歌街景请求?
- apache-spark - 什么样的数据,我们可以通过Spark处理??结构化/非结构化/半结构化?
- javascript - 使用适用于移动/桌面的 javascript 搜索 30k 谷歌工作表行的有效方法
- javascript - Slick JS垂直滚动连续,但不能拖动/触摸滑动