引发异常,如果脚本失败 [英] Raise exception if script fails

查看:172
本文介绍了引发异常,如果脚本失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,tutorial.py。我想从一个文件test_tutorial.py,这是我的Python测试套件中运行此脚本。如果tutorial.py执行没有任何异常,我想测试通过;如有异常tutorial.py的执行过程中引发的,我想测试失败。

I have a python script, tutorial.py. I want to run this script from a file test_tutorial.py, which is within my python test suite. If tutorial.py executes without any exceptions, I want the test to pass; if any exceptions are raised during execution of tutorial.py, I want the test to fail.

下面是我在写test_tutorial.py,这确实的不可以产生所需的行为:

Here is how I am writing test_tutorial.py, which does not produce the desired behavior:

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

我觉得上面的控制流不正确:如果tutorial.py抛出一个异常,那么断言线永远不会执行。

I find that the above control flow is incorrect: if tutorial.py raises an exception, then the assert line never executes.

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

What is the correct way to test if an external script raises an exception?

推荐答案

如果没有错误取值 0

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

或者使用

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 /除正赶上从教程文件没有,你可以将它移出一切,它会表现得一样的:

Your try/except is catching nothing from the tutorial file, you can move everything outside the it and it will behave the same:

from os import system
test_passes = False

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

assert test_passes

这篇关于引发异常,如果脚本失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆