AlwaysLearning
AlwaysLearning

Reputation: 8051

Multiple tests for output of a module reading standard input

In one coding exercise in my Udemy course, a student is required to write a program that checks whether the total length of three strings read from the standard input is equal to 10, i.e. a one-liner like this:

print(len(input()) + len(input()) + len(input())==10)

The module is called main.py. I am trying to test it:

import sys
from unittest import TestCase
from unittest.mock import patch

class Evaluate(TestCase):
    fake_input1 = iter(["a", "abcdefgh", "I"]).__next__
    fake_input2 = iter(["a", "b", "c"]).__next__

    @patch("builtins.input", fake_input1)
    def test1(self):
        import main
        output = sys.stdout.getvalue().strip()
        self.assertEqual("True", output, "Wrong output")

    @patch("builtins.input", fake_input2)
    def test2(self):
        import main
        output = sys.stdout.getvalue().strip()
        self.assertEqual("False", output, "Wrong output")

The first test works as expected. For test2, output is empty. I thought it had to do with the module being imported only once and tried to unimport it, but still could not get it to work. What is going on and how can I fix it?

Upvotes: 0

Views: 27

Answers (0)

Related Questions