嵌套if语句的Python单元测试 [英] Python unit test for nested if statement

查看:200
本文介绍了嵌套if语句的Python单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在发布单元测试题,因为我正试图擅长他们。我会尽量保持清醒。下面我有一个嵌套的if语句,我想模拟难度变量的输入,如果满足条件则检查stdout。

So I've been posting unit test questions because I'm trying to get good at them. I'll try to be as clear as possible. Below I have a nested if statement, I want to mock the input for the difficulty variable and check for the stdout if the condition is met.

这是我的运行代码..

here is my run code..

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语句,它工作正常。我不知道如何去做第二个。任何帮助表示赞赏,谢谢大家。

Now here's my unit test, but this is only for the first If Statement, which works fine. I don't know how to go about doing the second one. Any help is appreciated, thank you all in advance.

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()


推荐答案

您可以使用 side_effect 参数 patch 来制作输入返回第一次调用它,1第二次时间:

You can use the side_effect argument to patch to make input return "yes" the first time its called, and "1" the second time:

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

这篇关于嵌套if语句的Python单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆