Skip to content Skip to sidebar Skip to footer

Python Unit Test For Nested If Statement

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 f

Solution 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

Post a Comment for "Python Unit Test For Nested If Statement"