Ali Elkhateeb
Ali Elkhateeb

Reputation: 3743

Git pre-receive hook automatically run unit tests being pushed in the current ref

I am having a problem in my flow, I setup a pre-receive hook to run unit tests for branches master and dev as following:

#!/bin/bash
while read oldrev newrev ref
do
        if [[ ${ref} = refs/heads/master ]];
        then
                BRANCH=master
                WORKING_DIR="/var/www/project/project_api"
        elif [[ ${ref} = refs/heads/dev ]]
        then
                BRANCH=dev
                WORKING_DIR="/var/www/project/project_api_dev"
        else
                echo "Ref $ref received. Will not run unit tests."
        fi
done

if (test "$BRANCH" != ""); then
        echo "Running Unit Tests..."
        cd "$WORKING_DIR"
        npm test
        rc=$?
        if [[ $rc != 0 ]] ; then
                echo "Unit Tests FAILED"
                echo "Push is REJECTED"
                exit $rc
        fi

        echo "Unit Tests PASSED"
fi

exit 0

With this setup, I want to reject the push if one of the unit tests (being pushed) fail.

The issue is that it runs the tests that are already checked out to the working directory $WORKING_DIR, not the tests that are being pushed in the current ref.

I thought of always checking out the tests folder before running the npm test, but I am not sure if this is the right way to automate running unit tests before pushing.

Upvotes: 1

Views: 725

Answers (1)

VonC
VonC

Reputation: 1327634

The pre-receive hook is invoked... just before starting to update refs on the remote repository.

So your files won't reflect what you have pushed.

You should push to an intermediate "gate" repository, where a post-receveive hook would:

  • run the test
  • push to the actual target repository if they pass
  • send an email back and reset the target branch if they fail

Upvotes: 1

Related Questions