[Django]-Get pass or fail output from Django unit tests

4👍

You’re looking for the exit status ($?) of the manage.py test command, which exits with a status of 1 whenever at least one test fails (or for any error), otherwise exits with 0 when all tests pass.

Stdlib unittest also has the same behavior.

So in essence, you premise is wrong and actually your checking is not correct — you’re saving the STDOUT from python manage.py test in variable output in the first example, your second example would raise an error unless you have a package named 0 that has module(s) test*.py; if you have such a package then the second command will save both STDOUT and STDERR from the manage.py test 0 command as variable output.

You can either check for the exit status of the last command using $?:

python manage.py test
if [ $? = 0 ]; then
    # Success: do stuff
else
    # Failure: do stuff
fi

But there’s a better way, shells can check the exit status implicitly in if:

if python manage.py test; then
    # Success: do stuff
else
    # Failure: do stuff
fi

If you don’t care for STDOUT/STDERR, you can redirect those streams to /dev/null, POSIX-ly:

if python manage.py test >/dev/null 2>&1; then
    # Success: do stuff
else
    # Failure: do stuff
fi

Bash-ism (works in other advanced shells):

if python manage.py test &>/dev/null; then
    # Success: do stuff
else
    # Failure: do stuff
fi

Leave a comment