使用空用户输入对 Python 函数的返回值进行单元测试



我在fruit.py脚本中有一个函数,它根据用户输入返回一个Enum。

class Selection((IntEnum):
APPLE = 0
ORANGE = 1
PEAR = 2
MELON = 3
GRAPE = 4
def get_input():
selection = int(input("Input an integer from 0 to 4: "))
fruit = Selection(selection)
return fruit

现在我想在fruit_test.py中测试,如果用户输入为空,它是否会返回任何内容/引发错误:

import unittest
from unittest.mock import patch
import fruit
class TestCase(unittest.TestCase):
@patch('builtins.input', return_value=int(''))
def test_empty_input(self, input):
result = fruit.get_input()
self.assertEqual(result, "")

但是我的ValueError: invalid literal for int() with base 10: ''测试失败了。我理解这是因为我的补丁输入int('')是错误的,但我不知道如何编写正确的测试格式。有人知道怎么解吗?谢谢!

您可以将get_input函数转换为以下方式:

def get_input():
selection = input("Input an integer from 0 to 4: ")
if not selection.isnumeric() or not int(selection) Selection.__members__.values():
return None # or False or "" or whatever you want
fruit = Selection(int(selection))
return fruit

最新更新