如果脚本失败,则引发异常

时间:2015-01-10 02:24:39

标签: python exception-handling automated-tests control-flow

我有一个python脚本,tutorial.py。我想从文件test_tutorial.py运行这个脚本,该文件位于我的python测试套件中。如果tutorial.py执行没有任何异常,我希望测试通过;如果在执行tutorial.py期间引发任何异常,我希望测试失败。

以下是我编写test_tutorial.py的方法,会产生所需的行为:

from os import system
test_passes = False
try:
    system("python tutorial.py")
    test_passes = True
except:
    pass
assert test_passes

我发现上面的控制流是不正确的:如果tutorial.py引发异常,那么断言行永远不会执行。

测试外部脚本是否引发异常的正确方法是什么?

2 个答案:

答案 0 :(得分:4)

如果没有错误s将是0

from os import system
s=system("python tutorial.py")
assert  s == 0

或使用subprocess

from subprocess import PIPE,Popen

s = Popen(["python" ,"tutorial.py"],stderr=PIPE)

_,err = s.communicate() # err  will be empty string if the program runs ok
assert not err

你的try / except没有从教程文件中删除任何内容,你可以将所有内容移到它之外,它的行为也是一样的:

from os import system
test_passes = False

s = system("python tutorial.py")
test_passes = True

assert test_passes

答案 1 :(得分:0)

from os import system
test_passes = False
try:
    system("python tutorial.py")
    test_passes = True
except:
    pass
finally:
    assert test_passes

这将解决您的问题。

  如果出现任何错误,

Finally块将进行处理。请查看this以获取更多信息。如果不是with open()方法,通常会使用文件进程,以查看文件已安全关闭。

相关问题