简体   繁体   English

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

[英]Raise exception if script fails

I have a python script, tutorial.py. 我有一个python脚本,tutorial.py。 I want to run this script from a file test_tutorial.py, which is within my python test suite. 我想从文件test_tutorial.py运行这个脚本,该文件位于我的python测试套件中。 If tutorial.py executes without any exceptions, I want the test to pass; 如果tutorial.py执行没有任何异常,我希望测试通过; if any exceptions are raised during execution of tutorial.py, I want the test to fail. 如果在执行tutorial.py期间引发任何异常,我希望测试失败。

Here is how I am writing test_tutorial.py, which does not produce the desired behavior: 这里是我如何写test_tutorial.py, 产生所需的行为:

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

I find that the above control flow is incorrect: if tutorial.py raises an exception, then the assert line never executes. 我发现上面的控制流是不正确的:如果tutorial.py引发异常,那么断言行永远不会执行。

What is the correct way to test if an external script raises an exception? 测试外部脚本是否引发异常的正确方法是什么?

If there is no error s will be 0 : 如果没有错误,则s0

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

Or use 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

Your try/except is catching nothing from the tutorial file, you can move everything outside the it and it will behave the same: 你的try / except没有从教程文件中删除任何内容,你可以将所有内容移到它之外,它的行为也是一样的:

from os import system
test_passes = False

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

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

This is going to solve your problem. 这将解决您的问题。

Finally block is going to process if any error is raised. 如果出现任何错误, Finally块将进行处理。 Check this for more information.It's usually using for file process if it's not with open() method, to see the file is safely closed. 检查这一点以获取更多信息。如果不是with open()方法,通常用于文件处理,以查看文件是否安全关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM