Python单元测试模拟输入注册错误inpu

2024-04-19 09:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我对单元测试还很陌生,我试图弄清楚为什么模拟输入会读作'yes'我不知道为什么当我将输入模拟为'no'

这是我的运行代码。你知道吗

def main():

    newGame = input("")

    if newGame == "yes" or "y":
        print("TEST1")
    elif newGame == "no" or "n":
        print("TEST2")
    else:
        print("TEST3")

没什么疯狂的,直截了当的。这是我的测试代码。你知道吗

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

from RunFile import main

class GetInputTest(unittest.TestCase):

  @patch('builtins.input', return_value="no")
  def test_output(self,m):
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          main()
          output = out.getvalue().strip()
          self.assertEqual("TEST2",output)
      finally:
          sys.stdout = saved_stdout


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

还有,这是回溯。你知道吗

======================================================================
FAIL: test_output (__main__.GetInputTest)
----------------------------------------------------------------------
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_output
    self.assertEqual("TEST",output)
AssertionError: 'TEST2' != 'TEST1'
- TEST2
+ TEST1
?     +

就像我之前提到的,我不知道发生了什么。你知道吗

提前谢谢大家!你知道吗


Tags: notestimportselfoutputmainstdoutsys
1条回答
网友
1楼 · 发布于 2024-04-19 09:27:05

您的补丁程序实际上运行得很好;您刚刚在if语句中犯了一个错误。你真的想要这个:

def main():

    newGame = input("")

    if newGame == "yes" or newGame == "y":
        print("TEST1")
    elif newGame == "no" or newGame == "n":
        print("TEST2")
    else:
        print("TEST3")

可以更简洁地写为:

def main():
    newGame = input("")

    if newGame in ["yes", "y"]:
        print("TEST1")
    elif newGame in ["no", "n"]:
        print("TEST2")
    else:
        print("TEST3")

当前if语句的计算结果为if (newGame == "yes") or "y":。由于bool("y")True,if语句总是求值为True,这就是"TEST1"被打印的原因。你知道吗

相关问题 更多 >