如果脚本失败则引发异常

2024-02-01

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

这是我编写 test_tutorial.py 的方式,它的作用not产生所需的行为:

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

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

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


如果没有错误的话s0:

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

Or use 子流程 https://docs.python.org/2/library/subprocess.html:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果脚本失败则引发异常 的相关文章

随机推荐