Throw an exception if the script doesn't work
I have a python script, tutorial.py. I want to run this script from the test_tutorial.py file that is in my python test suite. If tutorial.py runs without any exceptions, I want the test to pass; if exceptions are thrown while running tutorial.py, I want the test to fail.
This is how I write test_tutorial.py that does not generate the desired behavior:
from os import system
test_passes = False
try:
system("python tutorial.py")
test_passes = True
except:
pass
assert test_passes
I found that the above control flow is wrong: if tutorial.py throws an exception, then the assert line is never executed.
What is the correct way to check if an external script is throwing an exception?
source to share
If there is no error it 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 attempt / exception is not catching anything from the tutorial file, you can move everything outside of this and it will behave the same:
from os import system
test_passes = False
s = system("python tutorial.py")
test_passes = True
assert test_passes
source to share
from os import system
test_passes = False
try:
system("python tutorial.py")
test_passes = True
except:
pass
finally:
assert test_passes
This will solve your problem.
Block
Finally
will be processed if any error occurs. this for more information. This is usually used to process a file if it is not a methodwith open()
to see the file safely closed.