Using Git pre-commit hooks: Automated Testing of Code with Python Unit Tests

This post show how a pre-commit git hook is implemented. The git hook is used to trigger a script which runs the unit test using my conda environment.

Using pre-commit hooks will prevent commit code with issues into your local repo and is preventing the developer from eventually pushing a broken build into the a remote repository

This is in tandem with a test driven approach, instead of having to run my tests separately, then commit, I have only need to commit. Personally, I find them to be really useful. For example, you can use them stop commits if files contain certain confidential data.

The pre-commit hook can be bypassed, but that's not what this post is about. We as developers need to be assured that we are not messing up every step of the way. 

Using pre-commit hooks can take some that pressure off as we work by automating the code testing as we work.

Do note that this works on a per-commit basis. It does not retrospectively check for for previous commits.


Steps to create and execute a pre-commit

First I create file pre-commit file. 



The shebang line #!/bin/sh is important. Here it is making this pre-commit file execute as a Shell Script. 


This is the Shell script that activates my conda environment and runs the unittest command to discover tests. Assuming that my Python project folder structure is properly maintained, all the unit tests I have written and stored in the test folder will be executed.

I have set it to exit with value of 1 if the previous command(lines 5-7) does not  evaluate to 0

With value of 1, the pre-commit hook fails



And the output of the result. I have changed my assertEqual method argument to False. This is done to  purposely fail the unit test to show that the pre-commit hook is preventing the commit to my local Git repo.




Python unit test purposely made to fail.







Comments

Popular posts from this blog

Test Driven Development: How and Why

Five Things I Wish I Knew When Starting with Python