Git hooks are scripts that we can define and which can be run when certain Git events happen. They can, for example, run tests before a commit and reject if it fails.
There are client-side hooks (run on your own computer when committing) and server-side hooks (run on server after pushing, usually used to test if merging is okay).
Here we will use our previous
example.py and add a git client-side hook the
pre-commit hook to run a script before a
commit is recorded.
We are still in the directory
def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 assert add('space', 'ship') == 'spaceship'
$ pytest example.py
$ git init
$ git add example.py $ git commit
Save this file as
#!/bin/bash pytest example.py
$ chmod +x pre-commit
$ mv pre-commit .git/hooks
pre-commit should reject the commit.
Discuss this approach: pros and cons.
Git hooks provide a convenient way to locally automatize tests.