I want to test with unittest a function in Python (2.7) that use different raw_input.
How can I achieve this?
Function (in module fc):
def main():
name = raw_input("name: ").lower()
surname = raw_input("surname: ").lower()
birth_date = raw_input("Birth date (dd/mm/yyyy): ").lower()
city = raw_input("city: ").lower()
sex = raw_input("sex (m/f): ").lower()
#other tasks...
test function:
import fc
import unittest
class test_main_fc(unittest.TestCase):
def test_main(self):
#how can I give to main the parameters that will ask?
self.assertEqual(fc.main(), 'rssmra80a01l781k')
if __name__ == '__main__':
unittest.main()
The solution I could find, this, works for 1 input passed at a time. I want to know how to pass different values to the main function.
This works for only 1 value of raw_input requested, in this case, name.
class test_main_fc(unittest.TestCase):
def test_fc_output(self):
original_raw_input = __builtins__.raw_input
__builtins__.raw_input = lambda _: 'mario'
#capturing the output
with captured_output() as (out, err):
fc.main()
output = out.getvalue().strip()
self.assertEqual(output, 'rssmra80a01l781k')
__builtins__.raw_input = original_raw_input
raw_input, but the function that uses its results. So either there is a function that processes values (regardless of where they were obtained from), or you inject intomaina function to use for getting input. The former case seems cleaner in general. The latter case allows you to stub the function in tests so it returns what you want.fake_inputis assigned to__builtins__.raw_input(as shown in the link you posted).