所以我一直在发布单元测试题,因为我试图擅长这些问题。我会尽量保持清醒。下面我有一个嵌套的if语句,我想模拟difficulty
变量的输入,如果条件满足则检查stdout。
这是我的运行代码..
def main():
print("''''''''''''''''''''''''''''''''''''")
print("''''''''''''''''''''''''''''''''''''")
print("''' \t\t\t\t '''")
print("''' \t\t\t\t '''")
print("''' \t Pirate Games\t\t '''")
print("''' \tStart a new game?\t '''")
print("''' \t\t\t\t '''")
print("''' \t\t\t\t '''")
print("''''''''''''''''''''''''''''''''''''")
print("''''''''''''''''''''''''''''''''''''")
newGame = input("").lower()
if newGame == "yes" or "y":
print("1.Scallywag\n2.Crew\n3.Pirate")
difficulty = input("Choose ye toughness!")
if difficulty == "1":
print("TEST")
elif newGame == "no" or "n":
print("Goodbye! Come Again")
else:
print("Enter correct input!")
现在这是我的单元测试,但这仅适用于第一个If语句,它运行正常。我不知道如何去做第二个。如有任何帮助,请提前感谢大家。
import unittest
from unittest.mock import patch
import io
import sys
from RunFile import main
class GetInputTest(unittest.TestCase):
@patch('builtins.input', return_value='yes')
def test_output(self,m):
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
self.assertEqual(output, "1.Scallywag\n2.Crew\n3.Pirate")
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
unittest.main()
答案 0 :(得分:6)
您可以使用patch
参数input
使"yes"
第一次返回"1"
,第二次class GetInputTest(unittest.TestCase):
@patch('builtins.input', side_effect=["yes", "1"])
def test_output(self,m):
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
# Make sure TEST appears at the end, in addition to the original list of items.
self.assertEqual(output, "1.Scallywag\n2.Crew\n3.Pirate\nTEST")
finally:
sys.stdout = saved_stdout
:
{{1}}