如何在 Python 控制台中输入并通过编程验证输出?

4

这个示例程序

N = int(raw_input());
n  = 0;
sum = 0;
while n<N:

    sum += int(raw_input());
    n+=1;

print sum;  

我有一组测试用例,因此需要一个Python程序来调用上述Python程序,给出输入并验证在控制台中打印的输出。


1
将其转换为函数,并用参数替换raw_input()。另外,不要在每行末尾加分号。Python不需要它们。 - Blender
@Blender 我正在解决这个难题,需要输入大量数据。我正在自动化这一部分。基本上,我想要模拟Interviewstreet对提交的程序所做的操作。而且,老习惯难改 :) - Sathish
3
你可以创建一个第二个函数,使用 raw_input() 获取用户输入并将其输入原始函数中。如果你将逻辑与用户交互分开,这将更容易实现。 - Blender
4个回答

3
在Unix shell中,可以通过以下方式实现:
$ python program.py < in > out  # Takes input from in and treats it as stdin.
                                # Your output goes to the out file.
$ diff -w out out_corr          # Validate with a correct output set

您可以使用Python来执行相同的操作,如下所示。
from subprocess import Popen, PIPE, STDOUT

f = open('in','r')            # If you have multiple test-cases, store each 
                              # input/correct output file in a list and iterate
                              # over this snippet.
corr = open('out_corr', 'r')  # Correct outputs
cor_out = corr.read().split()
p = Popen(["python","program.py"], stdin=PIPE, stdout=PIPE)
out = p.communicate(input=f.read())[0]
out.split()
# Trivial - Validate by comparing the two lists element wise.

1
拾起分离的思想,我会考虑这个:
def input_ints():
    while True:
        yield int(raw_input())

def sum_up(it, N=None):
    sum = 0
    for n, value in enumerate(it):
        sum += int(raw_input());
        if N is not None and n >= N: break
    return sum

它是相关的,打印总和

要使用它,您可以执行以下操作

inp = input_ints()
N = inp.next()
print sum_up(inp, N)

为了测试它,你可以做一些类似的事情

inp = (1, 2, 3, 4, 5)
assert_equal(sum_up(inp), 15)

能否提供一个完整的例子?脚本可以提供多行输入给自己或其他脚本吗? - WebComer

0

我写了一个测试框架(prego),可以用于解决你的问题:

from hamcrest import contains_string
from prego import TestCase, Task

class SampleTests(TestCase):
    def test_output(self):
        task = Task()
        cmd = task.command('echo your_input | ./your_app.py')
        task.assert_that(cmd.stdout.content, 
                         contains_string('your_expected_output'))

当然,prego提供的功能远不止这些。

-1
通常情况下,你会想以不同的方式组织你的代码,也许可以按照 Blender 在他的评论中建议的方式。然而,为了回答你的问题,你可以使用 subprocess 模块编写一个脚本来调用这个脚本,并将输出与预期值进行比较。
特别是要注意 check_call 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接