2
,我有以下的功能,我想测试:测试多次调用输入()
# Ask user input, returns year
def what_year():
# Get the first input from the user.
year = input('\n\tEnter the year you would like to START your range: \n\t')
# Catch the error if the user doesn't enter a convertable string.
try:
year = int(year)
except ValueError:
print(error_msg.format(year))
what_year()
# We only want years between 2005 and today's year.
if year not in range(2005, int(datetime.now().year +1)):
print(error_msg.format(year))
what_year()
return year
我想测试它,而无需提出任何错误,因为理想的功能会不断循环,直到用户输入可接受的输入为止。
我失去了如何让pytest循环输入。我尝试用mock修补builtins.input,并且为我的函数提供指定的输入,但理想情况下,测试将能够成功循环输入列表。
例如,从我的测试代码如下,在真实世界中,用户会首先查看所有无效选项,然后开始输入有效选项,并且函数最终会开始返回“年”。
我大概得到了解决此通过让我的每个功能,然后养值误差调试参数,如果调试是出于测试目的,但这似乎简陋:
功能:
# Ask user input, returns year
def what_year(debug=False):
# Get the first input from the user.
year = input('\n\tEnter the year you would like to START your range: \n\t')
# Catch the error if the user doesn't enter a convertable string.
try:
year = int(year)
except ValueError:
# Only raise ValueError if debug is on for testing purposes.
if debug:
raise ValueError
print(error_msg.format(year))
what_year(debug)
# We only want years between 2005 and today's year.
if year not in range(2005, int(datetime.now().year +1)):
if debug:
raise ValueError
print(error_msg.format(year))
what_year(debug)
return year
测试:
import mock
import pytest
from redditimagescraper import RedditImageScraper
@pytest.mark.parametrize('invalid_years', ["9999", "0", "", " ", "-2015"])
def test_what_year_invalid(invalid_years):
# Test invalid years
with pytest.raises(ValueError):
with mock.patch('builtins.input', return_value=invalid_years):
RedditImageScraper.what_year(True)
@pytest.mark.parametrize('valid_years', [str(year) for year in range(2005,2018)])
def test_what_year_valid(valid_years):
# Test valid years
with mock.patch('builtins.input', return_value=valid_years):
assert RedditImageScraper.what_year(True) == int(valid_years)
任何想法如何重写这个功能或测试功能更方便地测试投入?
不使用递归在Python中循环,使用'while'循环。但是如果你使用递归,你必须返回递归调用返回的内容:'return what_year(debug)' – Barmar
如果我将它改为while循环,Pytest会在每个输入调用中循环参数吗?或者我应该将return_value更改为side_effect,将参数化信息丢弃,并将其列入无效且有效的年份列表? – Ardeezy
对不起,我对pytest一无所知。但你不应该改变你的代码设计来匹配单元测试框架。 – Barmar