Raise exception if script fails

让人想犯罪 __ 提交于 2019-12-10 21:03:36

问题


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.

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

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?


回答1:


If there is no error s will be 0:

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:

from os import system
test_passes = False

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

assert test_passes



回答2:


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. 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.



来源:https://stackoverflow.com/questions/27872223/raise-exception-if-script-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!