gpt4 book ai didi

Python测试原始输入,if语句中的原始输入

转载 作者:太空狗 更新时间:2023-10-30 02:31:58 25 4
gpt4 key购买 nike

我目前正在测试我的 python 代码并且对 raw_input 有疑问。这是我的功能:

def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
return 'yes'
if ans == 'no':
some_value = raw_input('enter some value: ')
print 'you entered no'
return some_value

我正在以这种方式测试第一个 if 语句:

with mock.patch('__builtin__.raw_input', return_value= 'yes'):
assert answer() == 'yes'

但是我该如何检查 no 语句呢?我如何在模拟中进行模拟?

最佳答案

使用 side_effect :

with mock.patch('__builtin__.raw_input', side_effect=['yes']):
assert answer() == 'yes'
with mock.patch('__builtin__.raw_input', side_effect=['no', 'maybe']):
assert answer() == 'maybe'

根据 mock documentation :

If side_effect is an iterable then each call to the mock will return the next value from the iterable. The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):

>>>
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
...
StopIteration

关于Python测试原始输入,if语句中的原始输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com