嵌套if语句的Python单元测试

编程入门 行业动态 更新时间:2024-10-12 05:53:13
本文介绍了嵌套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单元测试

本文发布于:2023-11-24 02:27:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   语句   单元测试   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!