运维开发网

Python 2.7 – 让测试脚本模拟raw_input

运维开发网 https://www.qedev.com 2020-04-13 11:43 出处:网络 作者:运维开发网整理
我正在使用 Python 2.7来创建游戏.我想使用测试脚本来检查我的主文件中的方法,但我遇到了一个小问题.
我正在使用 Python 2.7来创建游戏.我想使用测试脚本来检查我的主文件中的方法,但我遇到了一个小问题.

在主脚本中,我询问用户是否想要使用raw_input()来玩游戏.不幸的是,这意味着当我使用Windows PowerShell运行测试脚本时,控制台会要求用户输入,我必须手动输入答案.经过反复测试,手动打字变得乏味.

(MWE和输出如下:这里,测试脚本应该生成’n’,因为它只检查方法,而不是游戏本身.实际的方法做一些计算,打印一个语句,并输出一个字符串.)

这让我想到了我的问题:

有没有办法编写一个自动为raw_input()生成输入的测试脚本?

或者,是否有其他方法可以接受测试脚本可以模拟的主游戏文件中的用户输入?

思考:在寻找答案的时候,我已经看到了一些关于模拟的信息…我之前没有使用过,而且模拟似乎从特定语句中断言结果,但我只是想让测试文件有效地绕过它提示.我可以从游戏脚本中删除那个(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>
我对此感兴趣,所以一些搜索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.如:

>在游戏功能中添加一个额外的输入,并从测试脚本中传递它>使用测试脚本中的参数启动游戏脚本

0

精彩评论

暂无评论...
验证码 换一张
取 消