gpt4 book ai didi

Python单元测试测试是模拟错误的输入

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:12 25 4
gpt4 key购买 nike

所以我正在练习单元测试,并且有以下代码。我使用 side_effects 第一次和第二次模拟输入,但断言失败,因为代码正在执行 else 语句,而不是预期的输出。这是我的运行代码。

def main():
answer = input("Would you like to create a pirate?! (yes/no)").lower()

if answer == 'y':

name = input("Enter the name of your pirate")
CreateAPirate(name, "Serpent", "100")

elif answer == 'n':
print("Okay! you chose not to create a pirate!")
else:
print("You must say Yes or No")


def CreateAPirate(name, ship, age, beard="NO"):
print("Capt:", name)
print("Pirate Ship:", ship)
print("Age:", age)
print("Do you have a beard?:", beard)
return

这是我的测试代码

import unittest
from unittest.mock import patch
import sys
from RunFile import main
import io

class TestSuite(unittest.TestCase):

@patch('builtins.input',side_effects=['y','test'])
def test_stdout_equals_Hello(self,m):

saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
main()
output = out.getvalue().strip()
self.assertEquals("Capt: test\nPirate Ship: Serpent\nAge: 100\nDo you have a beard?: NO",output)
finally:
sys.stdout = saved_stdout

if __name__ == "__main__":
unittest.main()

最后是我的 AssertionError 代码和回溯

Failure <Click to see difference>

Traceback (most recent call last):
File "C:\Python33\lib\unittest\mock.py", line 1087, in patched
return func(*args, **keywargs)
File "C:\Users\jsalce\Documents\Testsuites\IfStatements\Testsuite.py", line 18, in test_stdout_equals_Hello
self.assertEquals("Capt: test\nPirate Ship: Serpent\nAge: 100\nDo you have a beard?: NO",output)
AssertionError: 'Capt: test\nPirate Ship: Serpent\nAge: 100\nDo you have a beard?: NO' != 'You must say Yes or No'
+ You must say Yes or No- Capt: test
- Pirate Ship: Serpent
- Age: 100
- Do you have a beard?: NO

我知道出了什么问题..我只是不知道如何解决它。

最佳答案

您为第一个输入提供带有 side_effects 的字符串“yes”,但条件正在测试专门查找字符串“y”或“n”。

你可以对内置函数进行更改。输入,如果你同意你的队长也被命名为y,它就会起作用。我不认为 side_effects 是传递输入的方式。

class TestSuite(unittest.TestCase):

@patch('builtins.input')
def test_stdout_equals_Hello(self,m):

saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
ori = __builtins__.input
__builtins__.input = lambda x:'y'
main()
__builtins__.input = ori
output = out.getvalue().strip()
self.assertEquals("Capt: y\nPirate Ship: Serpent\nAge: 100\nDo you have a beard?: NO",output)
finally:
sys.stdout = saved_stdout

关于Python单元测试测试是模拟错误的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898402/

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