这个示例程序
N = int(raw_input());
n = 0;
sum = 0;
while n<N:
sum += int(raw_input());
n+=1;
print sum;
我有一组测试用例,因此需要一个Python程序来调用上述Python程序,给出输入并验证在控制台中打印的输出。
这个示例程序
N = int(raw_input());
n = 0;
sum = 0;
while n<N:
sum += int(raw_input());
n+=1;
print sum;
我有一组测试用例,因此需要一个Python程序来调用上述Python程序,给出输入并验证在控制台中打印的输出。
$ 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
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.
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)
我写了一个测试框架(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'))
check_call
方法。
raw_input()
。另外,不要在每行末尾加分号。Python不需要它们。 - Blenderraw_input()
获取用户输入并将其输入原始函数中。如果你将逻辑与用户交互分开,这将更容易实现。 - Blender