我有一个使用def get_valid_input(input_str: str, valid_options: tuple):
while True:
response = input(input_str)
if response in valid_options:
return response
raise InvalidOptionException('Invalid option')
函数的函数,如下所示:
InvalidOptionException
我需要测试当响应不是有效选项时引发异常Exception
,简单扩展class UtilTest(unittest.TestCase):
@patch('builtins.input', lambda: 'a')
def test_when_input_is_invalid_then_exception_is_raised(self):
self.assertRaises(
InvalidOptionException,
get_valid_input,
'', ('y', 'n')
)
。我有以下测试:
Error
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "/Users/user/mathsistor/chumme/test/test_util.py", line 13, in test_when_input_is_invalid_then_exception_is_raised
'', ('y', 'n')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 728, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 177, in handle
callable_obj(*args, **kwargs)
File "/Users/user/mathsistor/chumme/util.py", line 14, in get_valid_input
response = input(input_str)
TypeError: <lambda>() takes 0 positional arguments but 1 was given
但是,当我运行测试时,我收到以下错误:
{{1}}
我该如何解决这个问题?
答案 0 :(得分:2)
input
函数接受一个参数(提示字符串)。要模拟它,你必须使用带有一个参数的函数/ lambda:
@patch('builtins.input', lambda _: 'a')
当您不打算使用参数时,习惯使用下划线。