0

Suppose I have this code. Really unsure how to Unit test this seeing as it is a void method, requires user input, and the valid answer for one of the cases is to just call another method. Like how do I test this?

def start():
    user_Response = input(
        '\n' "○ Press 1 to Enter the Main Menu" '\n'
        "○ Press 2 or type 'exit' to Exit \n ")

    if user_Response == str(1):
        mainMenu()

    elif user_Response == str(2) or user_Response.lower() == "exit":
        print(
            'Thank you, good bye.
        exit()

    else:
        "Please enter a valid response."
        start() ```

1 Answers1

0

I would rewrite the function. Instead of calling input, I would pass a file-like object as an argument which you can iterate over. The caller can be responsible for passing sys.stdin or some other file-like object (such as an instance of io.StringIO) for ease of testing.

I would also ditch recursion in favor of a simple loop.

def start(input_stream):
    while True:
        print("...")
        user_response = input_stream.readline().rstrip('\n')

        if user_response == "1":
            return mainMenu()

        elif user_response == "2" or user_response.lower() == "exit":
            print('Thank you, good bye.')
            exit()

        else:
            print("Please enter a valid response.")
        

A sample test:

def test_loop():
    try:
        start(io.StringIO("exit"))
    except SystemExit:
        pass
    else:
        assert False, "start did not exit"

         
chepner
  • 497,756
  • 71
  • 530
  • 681