1

我有以下方法用于测试bcunix 命令......它需要一个表达式,执行它并取回输出......

def run_test(expr=""):

        try:
            process = sp.Popen('bc',
                               stdin=sp.PIPE,
                               stdout=sp.PIPE,
                               stderr=sp.PIPE)
            process.stdin.write(expr)
            result = process.stdout.readline()
            process.stdin.close()
            retval = process.wait()
            return result
        except Exception, e:
            print e


# correct expression, returns '4'
print run_test('2+2\n') 

但是,当我传递错误的表达式时expr,我想正确处理错误,因此我可以断言测试用例expr正确失败......

#never stops
print run_test('2 / 0\n')

但是,上面的表达式永远不会返回......我想返回一个值,例如 false,它会告诉我表达式无效,然后当我断言时,

assertTrue(run_test('2 / 0\n'), False) 

会正常工作......我怎样才能实现它?

4

2 回答 2

1

发生的事情是 stderr 没有被正确重定向。在执行 readline 时,您需要通过 python 提示符下的以下命令将 stderr 重定向到 stdout。您需要将其移至您的功能。

   def run_test(expr=""):

        try:
            process = sp.Popen('bc',
                               stdin=sp.PIPE,
                               stdout=sp.PIPE,
                               stderr=sp.STDOUT)
            process.stdin.write(expr)
            result = process.stdout.readline()
            process.stdin.close()
            retval = process.wait()
            return result
        except Exception, e:
            print e


# correct expression, returns '4'
print run_test('2+2\n') 

print run_test('2 / 0\n') # now this stops too

文档说:http : //docs.python.org/2/library/subprocess.html 可用作 Popen 的 stderr 参数的特殊值,指示标准错误应与标准输出进入相同的句柄。

于 2013-10-24T13:36:39.653 回答
0
  1. Your best bet would be to actually do things in python as some programs never guarantee to return something sensible.

  2. Next best would be to avoid calling programs in interactive mode but only in command line mode.

  3. After that you could try always appending the exit for the program that you are calling, e.g. for bc use process.stdin.write(expr + "\nquit\n").

  4. Last and worst would be to start a timer and if the expression does not terminate before the timer expires kill the process and give a time out error.

于 2013-10-24T05:08:43.217 回答