简体   繁体   中英

Unit Testing for user input and expected output in Python

I'm fairly new to unit test in Python, but have done a few so I understand the basics of it. One problem I'm having is being able to mock input and then test for the STDOUT based on that mocked input. I tried the solution in this post: python mocking raw input in unittests but didn't find any success with the given method. My test seems like it's getting hung up when asking for the input. I want to be able to mock the input for the Run module and then be able to test for the STDOUT which can be either True/False Here is my Run code

#imports
import random

def main():
    #variables
    dolphins = random.randrange(1,11)

    guess = int(input("This is a prompt"))

    print(guess == dolphins)

Really simple here. Here is my Testsuite

import unittest
from unittest.mock import patch

from Run import *

class GetInputTest(unittest.TestCase):

  @patch('builtins.input', return_value=1)
  def test_answer_false(self, input):
    self.assertEqual(main(), 'False')


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

So here I am feeding the input a value of 1 and then call the main() during my assertion and expect a value of False but it doesn't even get that far, the program just continuously runs, I think because it's waiting for an input and I may not be mocking it correctly. I also tried feeding builtins.input into the @patch parameter and I get the same result.

There's no error messages or tracebacks. Hopefully someone with a little more experience can tell me what I am doing wrong. Thank you all in advance for helping me out.

You can make your main as a function that takes arguments instead.

def main(args):
    ...do stuff

if __name__ == '__main__':
    args = input('Get input')
    main(args)

Then just unittest it as a normal function.

class TestMain(unittest.TestCase):
    def testmain(self):
        self.assertTrue(main(5), 'foo')

If you still want to have the input within your main, then you need to mock patch input not main .

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