【问题标题】:Unittest a Python function's return value with empty user input使用空用户输入对 Python 函数的返回值进行单元测试
【发布时间】:2021-12-10 06:02:04
【问题描述】:

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

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('') 错误,但我不知道如何编写正确的测试格式。有谁知道如何解决这个问题?谢谢!

【问题讨论】:

  • 测试告诉你正确的事情 - 这 not 目前是正确的期望,如果输入不能被解析为你的实现不会返回空字符串整数。所以要么实现需要改变,要么测试需要反映你期望它做什么。

标签: python python-3.x unit-testing testing python-unittest


【解决方案1】:

您可以将 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

【讨论】:

  • 是否可以在不修改get_input()函数的情况下进行测试?例如,我知道空输入会引发错误TypeError: __call__() missing 1 required positional argument: 'value' 和 8 会引发ValueError: 8 is not a valid Selection 有没有办法测试这些异常和错误? AssertRaises()够了吗?
猜你喜欢
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多