1

I have a method that takes user inputs and validates them until they enter a correct value. I am not sure how to write a unit test for this method since it already validates the user input.

def refreshtime_validation():
    while True:
        try:
            runtime_input = float(raw_input("Enter Refresh Time (in seconds): "))
        except ValueError:
            print "\n**Please enter a valid number (Must be an integer).**\n"
            continue
        if runtime_input <= 0:
            print "\n**Please enter a valid number (Must be greater than 0).**\n"
            continue
        else:
            return runtime_input

How do I go about in writing a unit test for this method? The only one I have so far is

self.assertEquals('1','1')    
self.assertEquals('100','100')
self.assertEquals('100000','100000')
adamn11
  • 311
  • 1
  • 4
  • 15

1 Answers1

3

You can use mock to mock a raw_input in Python and you can capture standard output by redirecting sys.stdout to a StringIO. This way you can mock your function input and test both invalid and valid cases:

import sys
import mock
import unittest
import StringIO
import __builtin__


# [..] your code


class Test(unittest.TestCase):
    @mock.patch.object(__builtin__, 'raw_input')
    def test_refreshtime_validation(self, mocked_raw_input):
        my_stdout = StringIO.StringIO()
        sys.stdout = my_stdout
        mocked_raw_input.side_effect = ['error', '0', '1']
        outputs = '\n**Please enter a valid number (Must be an integer).**\n'+\
            '\n\n**Please enter a valid number (Must be greater than 0).**\n\n'
        valid_value = refreshtime_validation()
        sys.stdout = sys.__stdout__
        self.assertEquals(my_stdout.getvalue(), outputs)
        self.assertEquals(valid_value, 1)


unittest.main()
Aurora Wang
  • 1,822
  • 14
  • 22