你如何使用@patch 装饰器来修补内置的 input() 函数?
例如,这是我想测试的 question.py 中的一个函数,其中包含对 input() 的调用:
def query_yes_no(question, default="yes"):
""" Adapted from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input """
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
这是我的测试,它给了我错误“ImportError: No module named ' builtins '”:
import unittest
from unittest.mock import patch
import question
class TestQueryYesNo(unittest.TestCase):
@patch('__builtins__.input.return_value', 'y')
def test_query_y(self):
answer = question.query_yes_no("Blah?")
self.assertTrue(answer)