2

I'd like to create a bash script which runs various tests (unit, integration, api tests etc.) on a certain code base. I'd like to enforce this script to run all tests on every build and let the build only fail, if at least one of the test runs failed.

I have a working solution but it feels bad to me. I would appreciate if anyone has an idea to inprove this.

#!/usr/bin/env bash

set -e 

#...
#some other code which should let the build fail immediately if something is wrong

set +e
runUnitTests.sh
unitTestsFailed=$?

runIntegrationTests.sh
integrationTestsFailed=$?

runApiTests.sh
apiTestsFailed=$?

if [ $unitTestsFailed -ne 0 ] || \
   [ $integrationTestsFailed -ne 0 ] || \
   [ $apiTestsFailed -ne 0 ]; then

    echo "Automated tests failed"
    exit 1
else
    echo "Automated tests succeeded"
    exit 0
fi
1

2 Answers 2

5

You can run each of the test scripts with a common function that checks for failure and sets a flag on error.

failure=0

testSuite() {
    "$@" || failure=1
}
testSuite runUnitTests.sh
testSuite runIntegrationTests.sh
testSuite runApiTests.sh
if ((failure)); then
    echo "Automated tests failed" >&2
    exit 1
else
    echo "Automated tests succeeded" >&2
    exit 0
fi
Sign up to request clarification or add additional context in comments.

Comments

0

You could check the result of the last executed command thanks to the $? variable :

./runUnitTests.sh && ./runIntegrationTests.sh && ./runApiTests.sh

if [ $? -eq 0 ]; then
    echo "Automated tests succeeded"
else
    echo "Automated tests failed"
    exit 0
fi

2 Comments

This is the easiest way. I personally might be tempted to have a counter instead and count if counter!=0 if I care which scripts failed (it sounds like they do care because they want ALL scripts run, us opposed to only running until first failure). but it depends on what they actually want from it and if they want to capture separate exit codes etc. In this example if more than one script fails then the exist status of the first script to fail will be returned
Thanks for your solution. But unfortunately this would stop the script as soon as there is an error in runUnitTests.sh (the first script). I would like to run ALL scripts and display it's reports at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.