命令行交互的Python单元测试

时间:2020-05-06 22:09:46

标签: python-3.x stdout stdin python-unittest

我正在尝试通过命令行交互来创建程序,然后使用unittest对其进行测试。我不确定如何使用模拟,这是我在SO上其他解决方案中所看到的。

我从投票表决的答案中得出了半解决方案的逻辑 Python: Write unittest for console print (对于python 3)

test / test_forecast.py:

import unittest
from weather import forecast as f
import io
import sys

class TestForecast(unittest.TestCase):
    def test_optimistic_forecast(self):
        captured_output = io.StringIO()
        sys.stdout = captured_output

        forecast = f.Forecast()
        forecast.start()

        sys.stdout = sys.__stdout__

        expected_text = "Welcome to the Forecaster\n" \
                        "Do you think it's going to be sunny tomorrow? " \
                        "Thanks for that optimistic forecast\n" \
                        "Do you think it's going to a nice weekend? " \
                        "Thanks for that optimistic forecast\n"

        self.assertEqual(expected_text, captured_output.getvalue())

天气/forecast.py

class Forecast:
    def start(self):
        print('Welcome to the Forecaster')

        response = input("Do you think it's going to be sunny tomorrow? ")
        if response == 'y':
            print('Thanks for that optimistic forecast')
        elif response == 'n':
            print('Maybe another day')

        response = input("Do you think it's going to a nice weekend? ")
        if response == 'y':
            print('Thanks for that optimistic forecast')
        elif response == 'n':
            print('Maybe another time')

我可以通过测试,但是必须两次键入“ y”,随着交互变得越来越复杂,我需要避免这种情况。

有没有办法让测试做到这一点,几乎就像标准输出一样,但标准输入是什么?

0 个答案:

没有答案