1

I'm testing a method in python that accepts input from a console menu and then launches a method depending on the input. For some reason, my test fails to launch when a number is used in the test, but not a string. This doesn't occur in the normal flow of my python script.

Here are my two tests:

    def test_invalid(self):
    out = StringIO()
    sys.stdout = out
    main.launch_menu_choice("hello")
    output = out.getvalue().strip()
    assert output == 'Invalid selection, please try again.'

def test_one(self):
        out = StringIO()
        sys.stdout = out
        main.launch_menu_choice('1')
        output = out.getvalue().strip()
        print output
        assert output == 'where do you want to load your file: '

part of my code that I'm testing

def launch_menu_choice(choice):
    if choice == '':
        main_menu_actions['main_menu']() 
    else:
        try:
            main_menu_actions[choice]()
        except KeyError:
            print "Invalid selection, please try again.\n"
    return

def load():
    print "where do you want to load your file: "
    path = raw_input(" >> ")
    ...
    return

main_menu_actions is a dict. 1 is add. For some reason test_invalid works fine while test invalid hangs while it says it is launching unittests. I don't understand what is happening.

Jonathan
  • 479
  • 3
  • 8
  • 17
  • Possible duplicate of [python mocking raw input in unittests](https://stackoverflow.com/questions/21046717/python-mocking-raw-input-in-unittests) – snakecharmerb Nov 18 '17 at 11:24
  • The test hangs because the `raw_input` statement in `load` is waiting for input. Also you are overriding `sys.stdout` and not reinstating it later, which may cause confusion. The answers in the suggested duplicate explain how to handle these issues using the `mock` library (`pip install mock` for python 2.7) or *context managers* (part of the standard library in python 2.7. – snakecharmerb Nov 18 '17 at 11:28
  • @snakecharmerb does that mean I can't test this if I can't remove the second raw_input call? I'm assuming that even if I pull out raw_input into a separate method like in the linked answer, I'll still run into this issue. – Jonathan Nov 18 '17 at 16:22

0 Answers0