Test before you push upstream with Git hooks

posted by 1 year ago and updated 1 year ago

Please read our previous blog post A tale of Sourcetree and Git hooks. This article presupposes to have knowledge on Git Hooks.

At Under the Coco Tree we strive for automation. It is one of our core values. How can we automate redundant tasks in order to free our time and focus to being more creative. Sometimes by doing this we spend more time that intended. Automation is always worth it in the long run.

Despite having Continuous Integration in place which performs the automated testing we want our developers to be more responsible.

This week we had a look at how run a test before pushing upstream to our master repo. We will be using Behat and Phpunit in this instance.

Our Requirements

  • Run tests on the local development machine
  • Run tests before pushing upstream to the master branch

Solution

  • Create a local git hook .git/hooks/pre-push that runs before pushing upstream.
  • Filter the branch to figure out if it is the master branch

First copy the pre-push hook. This script will run before pushing upstream.

cd .git/hooks/
cp pre-push.sample pre-push

Copy the script below into .git/hooks/pre-push

#!/bin/zsh
source ~/.zshrc

set -e

# Which branch are we on
branch="$(git rev-parse --abbrev-ref HEAD)"

# If we are on master
if [ $branch = "master" ]; then

    # Behat
    printf "\e[1;33mpre-push:\e[0m: Behat\n"
    behat
    if [ $? -eq 0 ]
    then
        printf "\e[1;32mSuccessful:\e[0m Behat\n"
    else
        printf "\e[1;31mError:\e[0m Behat\n"
        exit 1
    fi

    printf "\n\n=========================================\n"

    # Phpunit
    printf "\e[1;33mpre-push:\e[0m: PhpUnit\n"
    phpunit
    if [ $? -eq 0 ]
    then
        printf "\e[1;32mSuccessful:\e[0m PhpUnit\n"
    else
        printf "\e[1;31mError:\e[0m PhpUnit\n"
        exit 1
    fi
fi

exit 0

The magic lines

First we ask git to give us the name of the current branch we are pushing.

branch="$(git rev-parse --abbrev-ref HEAD)"

We then run the tests if we are on the master branch.

if [ "$branch" = "master" ]; then

What if I don't want to run the tests before pushing to master?

Ahhh, of course! Sometimes you might not want to run the hooks. Git's --no-verify parameter is here to the rescue.

git push --no-verify

By now you should have realized that we can't count on git hooks for our quality control. Simply because they can be bypassed. Nevertheless, git hooks are a great addition and give a solution to the repetitive tasks of testing. In order to make sure that your master branch is always deployable you need continues integration that runs automated tests.


Want to read more? Follow these links.