python - 我对python测试很陌生。帮助这个方法解释单元测试
问题描述
该函数将接受输入并根据输入调用登录函数。
def login_features():
print("Choose option to login")
print("1. BDO login")
print("2. GPM login")
print("3. Member login")
login_input = int(input())
switcher = {
1: bdo_login,
2: gpm_login, # I am calling the function instance
3: member_login
}
login = switcher.get(login_input, login_features)
login() # Executing the called function
解决方案
我假设您想为login_features()
. 一般来说,我会这样重构函数:
def execute_login_option(opt_str: str):
switcher = {...}
login = switcher.get(login_input, login_features)
login() # Executing the called function
def login_features():
print("Choose option to login")
print("1. BDO login")
print("2. GPM login")
print("3. Member login")
login_input = int(input())
execute_login_option(login_input)
这样您就可以轻松地进行测试execute_login_option
而无需修补input()
.
如果你需要产生一些输入,你可以使用 Python 的unittest.mock.patch
:
def my_function_with_input():
test = input("please enter a value")
return test
with mock.patch('%s.input' % __name__) as patched_input:
patched_input.return_value = "foo"
assert my_function_with_input() == "foo"
在上下文中,我将调用的返回值重新定义input()
为 be "foo"
。同样,您可以在测试用例中将返回值设置为所需的用户输入login_features
。
编辑(回答评论中关于如何测试不返回值的函数的问题):
如果您的函数没有返回要断言的值,它通常会将整个系统的状态更改为副作用(在您的示例中,这样的副作用可能是用户已登录)。请参阅下面有关如何在此类设置中进行测试的最小示例:
from unittest import mock
class ClassToTest:
def __init__(self):
self.state = "A"
def my_function_with_input(self):
test = input("please enter a value")
if test == "foo":
self.state = "B"
else:
self.state = "C"
def my_function_with_input():
test = input("please enter a value")
return test
with mock.patch('%s.input' % __name__) as patched_input:
patched_input.return_value = "foo"
test_obj = ClassToTest()
assert test_obj.state == "A"
test_obj.my_function_with_input()
assert test_obj.state == "B" # assert that the state changed to B
使用unittest.mock -framework可以利用更多的选项和可能性。
推荐阅读
- python - 如何在字符串中间用前导零填充数字?
- python-3.x - 导入错误:在 conda 环境中更新 python 时无法导入名称“secure_write”
- angular - 离子 ngModel ngModel 不适用于 Form
- javascript - 如何让 Figma API 与 Google App-script API 一起使用?
- javascript - 单击按钮添加“未定义”而不是项目
- vba - 使用双 where 子句访问动态过滤列表框
- r - 使用 stat_summary 绘制中位数的位置
- git - CircleCI 忽略 git 标签过滤器
- yii2 - 无法打开输入文件:yii 当我开始 rbac 迁移时
- python - Flask 使用“OnClick”运行 python 脚本:误报激活