0

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?

3
  • Multiple imports of the same module don't re-execute the code. You should define a function in main.py and call the function to execute it repeatedly. Commented May 24, 2024 at 14:46
  • 1
    Or you could use importlib.reload(), which would re-execute the code. Commented May 24, 2024 at 18:54
  • @MrBeanBremen Ah, I needed to both import and reload. Now it worked. Thank you. Commented May 25, 2024 at 18:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.