简体   繁体   中英

Output is empty when mocking input in Python Unit Test

So I've been having this issue for some time and can't find a solution.I have this run code which is pretty basic. I want to test for the expected output, "TEST" ,when I use side_effects to mock the input. The first time the input function is called I mock 'y' and then I mock '1' the second time it's called, which should then trigger the print statement. The problem is the output that is coming back is empty. I don't know whats going on, but when I run the main method manually and enter the inputs I get the expected output so I know the run code works as intended, but something funky is happening during the test.

here is my run code

def main():

    newGame = input("")

    if newGame == 'y':
        print("1.Scallywag\n2.Crew\n3.Pirate")

        difficulty = input("")

        if difficulty == '1':
            print("TEST")


main()

and here is my test code

import unittest
from unittest.mock import patch
import io
import sys

from Run import main

class MyTestCase(unittest.TestCase):

    @patch('builtins.input', side_effects=['y','1'])
    def test_output(self,m):
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          main()
          output = out.getvalue().strip()
          self.assertIn("TEST", output)
      finally:
          sys.stdout = saved_stdout


if __name__ == "__main__":
  unittest.main()

and here is the AssertionError i get back along with the trace back, take note that its expecting "" which shouldn't be the case.

F
======================================================================
FAIL: test_output (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python33\lib\unittest\mock.py", line 1087, in patched
    return func(*args, **keywargs)
  File "C:\Users\jsalce\Desktop\Testcases\Test.py", line 20, in test_output
    self.assertIn("TEST", output)
AssertionError: 'TEST' not found in ''

----------------------------------------------------------------------
Ran 1 test in 0.006s

FAILED (failures=1)

Thank you all in advance

Print("String", file=out)

这是您想要的,但是您需要传递给main。

You patch for input does not work as required because you are not giving it a function. Try this:

import unittest
from unittest.mock import patch, MagicMock
import io
import sys

from Run import main

class MyTestCase(unittest.TestCase):

    #@patch('builtins.input', side_effects=['y','1'])
    @patch('builtins.input', MagicMock(side_effect=['y','1']))
    def test_output(self):
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          main()
          output = out.getvalue().strip()
          self.assertIn("TEST", output)
          #I used equals to see if I am truly grabbing the stdout
          #self.assertEquals("TEST", output)
      finally:
          sys.stdout = saved_stdout

if __name__ == "__main__":
  unittest.main(verbosity=2)

And also, you do not need variable 'm' in your test_output signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM