Python 2.7 -- have test script simulate raw_input Python 2.7 -- have test script simulate raw_input powershell powershell

Python 2.7 -- have test script simulate raw_input


I was interested in this so did some searching for raw_input redirection. Austin Hashings suggestion work when you use it inside the script where raw_input is called:

import sysimport StringIOdef game_method(stuff):    """Calculates stuff for game"""    stuff_out = 'foo'    return stuff_out# Specity your 'raw_input' inputs = StringIO.StringIO("n")sys.stdin = s""" Check user wants to play the game """startCheck = raw_input('Would you like to play the game? (y/n) > ')sys.stdin = sys.__stdin__if (startCheck.lower() == 'y'):    play = Trueelse:    play = False""" Set up a game to play"""while (play==True):    # Do stuff    stuff_out = game_method(stuff)else:    print "\n\tGoodbye.\n\n"

Unfortunately, this doesn't seem to work outside of the script. This question looks at the problem and the general consensus is that you don't really need to include raw_input in your testing as its a language function, so you can pass in the input using some other method and simply mimic the raw_input using some other method such as:

  • Add an additional input to your game function and pass it from your test script
  • Launch the game script with arguments from your test script


import MWEdef check_game(input):    string_out = MWE.game_method(input)    return string_out""" Test code here """input = 7old_sysin = sys.stdinserver_input = cStringIO.StringIO("y" + "\n")sys.stdin = server_inputstring_output = check_game(input)print "===============\n%s\n===============\n\n\n" % (string_output == 'foo')