Making a job fail in jenkins

If your script exit with a non-zero status the build should fail.

import sys
sys.exit(-1)

The important thing is that the run of your python script is the last step of your jenkins job when it throws an exception or a non-zero exception code. If you run anything else after that, even echo "my job is done" will change the error code.

For me the following fails my jenkins job

echo "exit(1)" >> test.py
python test.py

When I do the following my jenkins job shows up as successful

echo "exit(1)" >> test.py
python test.py
echo "This changes my exit code back to 0, which is successful"

You can raise an exception at any point. If it goes unhandled, the application will stop. You don't even need to specify which exception you're raising.

if not yourTestHere:
    raise

If you want to specify a message, you can just raise a standard exception.

from exceptions import Exception
if not yourTestHere:
    raise Exception("Script failed because of bla bla bla")