Python unittest для взаимодействия с командной строкой - PullRequest
0 голосов
/ 07 мая 2020

Я пытаюсь создать программу с использованием командной строки, а затем протестировать ее с помощью unittest. Я не уверен, как использовать макеты, что я видел в других решениях на SO.

Я взял logi c для своего полуработающего решения из проголосованного ответа на Python: Записать unittest для консольной печати (для 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())

weather / прогноз.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», чего в будущем мне следует избегать, поскольку взаимодействие становится более сложным.

Есть ли способ заставить тест сделать это , почти так же, как читается стандартный вывод, но для стандартного ввода?

...