HowToWriteTests

From Git SCM Wiki
Jump to: navigation, search

This page describes how to write test cases for git. You will have found that there are some shell scripts in the t/ directory. They all follow more or less this simple example:

#!/bin/sh
#
# Copyright (c) 2007 <Your Name Here>
#

test_description='git-<command>'

. ./test-lib.sh

test_expect_success '<description>' '

        <the commands>

'

test_done

So when you have found something which does not work, write such a test case. (Do not bother about the number in the filename at first, this can always be determined later.)

Notes:

  • Once you included "test-lib.sh", an empty repository is set up in t/trash/. No need to initialise the repository yourself.
  • It is common that the first "test case" is called "setup", and sets up some files and commits to be used later.
  • The commands should always be connected by "&&", i.e.
echo Hello > file &&
git add file &&
...
  • Before a "git commit", execute the test function "test_tick", like this:
test_tick &&
git commit -m blub

This enforces reproducible timestamps (and thus, commit names) on the commits.

  • Instead of
echo A > A &&
git add A &&
test_tick &&
git commit -m A

you can use the shortcut

test_commit A
  • When comparing some output to a given expected output, the common idiom is something like this:
cat > expect << \EOF
...
EOF

test_expect_success 'narf' '

       ... > output &&
       git diff expect output

'

The backslash before "EOF" means that strings in the text beginning with a dollar sign are not interpreted as variables.

Basically, you can use all your usual shell script skills. But there are a few caveats:

  • 'echo -n' is not portable; use 'printf' instead.
  • 'sed -i' is not portable; use 'sed < $f >$f- && mv $f- $f' instead.
  • 'sed' "fixes" a missing newline at the end on some platforms. If you need to keep the last line without a newline, add the last line with 'echo "..." | tr -d '\n' >> file'.

Personal tools