Python 2.7 – 让测试脚本模拟raw_input
我正在使用
Python 2.7来创建游戏.我想使用测试脚本来检查我的主文件中的方法,但我遇到了一个小问题.
在主脚本中,我询问用户是否想要使用raw_input()来玩游戏.不幸的是,这意味着当我使用Windows PowerShell运行测试脚本时,控制台会要求用户输入,我必须手动输入答案.经过反复测试,手动打字变得乏味. (MWE和输出如下:这里,测试脚本应该生成’n’,因为它只检查方法,而不是游戏本身.实际的方法做一些计算,打印一个语句,并输出一个字符串.) 这让我想到了我的问题: 思考:在寻找答案的时候,我已经看到了一些关于模拟的信息…我之前没有使用过,而且模拟似乎从特定语句中断言结果,但我只是想让测试文件有效地绕过它提示.我可以从游戏脚本中删除那个(y / n)提示符,但这似乎是一个很好的学习机会…… MWE.py(游戏文件) def game_method(stuff): """Calculates stuff for game""" stuff_out = 'foo' return stuff_out """ Check user wants to play the game """ startCheck = raw_input('Would you like to play the game? (y/n) > ') if (startCheck.lower() == 'y'): play = True else: play = False """ Set up a game to play""" while (play==True): # Do stuff stuff_out = game_method(stuff) else: print "ntGoodbye.nn" MWE-test.py(测试脚本) import MWE def check_game(input): string_out = MWE.game_method(input) return string_out """ Test code here """ input = 7 string_output = check_game(input) print "===============n%sn===============nnn" % (string_output == 'foo') 控制台输出: PS C:dir> python MWE-test.py Would you like to play the game? (y/n) > n Goodbye. ===True=== PS C:dir> 解决方法
我对此感兴趣,所以一些搜索raw_input重定向.当你在调用raw_input的脚本中使用它时,Austin Hashings建议工作:
import sys import StringIO def game_method(stuff): """Calculates stuff for game""" stuff_out = 'foo' return stuff_out # Specity your 'raw_input' input s = 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 = True else: play = False """ Set up a game to play""" while (play==True): # Do stuff stuff_out = game_method(stuff) else: print "ntGoodbye.nn" 不幸的是,这似乎不适用于脚本之外. This question查看了这个问题,普遍的共识是你不需要在测试中包含raw_input作为它的语言函数,所以你可以使用其他方法传入输入,并使用其他方法简单地模仿raw_input.如: >在游戏功能中添加一个额外的输入,并从测试脚本中传递它>使用测试脚本中的参数启动游戏脚本 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |