我使用Python 2.7创建游戏。我想使用测试脚本检查主文件中的方法,但我遇到了一个小问题。
在主脚本中,我使用raw_input()
询问用户是否想要玩游戏。不幸的是,这意味着当我使用Windows PowerShell运行测试脚本时,控制台会要求用户输入,我必须手动输入答案。经过反复测试,手动打字变得乏味。
(MWE和输出如下:在这里,测试脚本应该生成一个' n'因为它只检查方法,而不是游戏本身。实际的方法做了一些计算,打印一个语句,并输出一个字符串。)
这让我想到了我的问题:
有没有办法编写一个自动为raw_input()
生成输入的测试脚本?
或者,是否有其他方法可以接受测试脚本可以模拟的主游戏文件中的用户输入?
思考:在搜索答案时,我已经看到了有关mock
的一些信息......我之前没有使用过这个问题,而且似乎断言似乎断言来自特定语句的结果,但我只是希望测试文件有效地绕过该提示。我可以从游戏脚本中删除那个(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 "\n\tGoodbye.\n\n"
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%s\n===============\n\n\n" % (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>
答案 0 :(得分:0)
我对此感兴趣,因此搜索了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 "\n\tGoodbye.\n\n"
不幸的是,这似乎不适用于脚本之外。 This question着眼于问题,普遍的共识是你不需要在测试中包含raw_input
作为语言函数,所以你可以使用其他方法传递输入并简单地使用其他方法模仿raw_input
,例如:
答案 1 :(得分:0)
import MWE
def check_game(input):
string_out = MWE.game_method(input)
return string_out
""" Test code here """
input = 7
old_sysin = sys.stdin
server_input = cStringIO.StringIO("y" + "\n")
sys.stdin = server_input
string_output = check_game(input)
print "===============\n%s\n===============\n\n\n" % (string_output
== 'foo')