]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: add simple tests for online help
[notmuch] / test / test-lib.sh
1 #!/usr/bin/env bash
2 #
3 # Copyright (c) 2005 Junio C Hamano
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see http://www.gnu.org/licenses/ .
17
18 if [ ${BASH_VERSINFO[0]} -lt 4 ]; then
19     echo "Error: The notmuch test suite requires a bash version >= 4.0"
20     echo "due to use of associative arrays within the test suite."
21     echo "Please try again with a newer bash (or help us fix the"
22     echo "test suite to be more portable). Thanks."
23     exit 1
24 fi
25
26 # if --tee was passed, write the output not only to the terminal, but
27 # additionally to the file test-results/$BASENAME.out, too.
28 case "$GIT_TEST_TEE_STARTED, $* " in
29 done,*)
30         # do not redirect again
31         ;;
32 *' --tee '*|*' --va'*)
33         mkdir -p test-results
34         BASE=test-results/$(basename "$0" .sh)
35         (GIT_TEST_TEE_STARTED=done ${SHELL-sh} "$0" "$@" 2>&1;
36          echo $? > $BASE.exit) | tee $BASE.out
37         test "$(cat $BASE.exit)" = 0
38         exit
39         ;;
40 esac
41
42 # Keep the original TERM for say_color and test_emacs
43 ORIGINAL_TERM=$TERM
44
45 # For repeatability, reset the environment to known value.
46 LANG=C
47 LC_ALL=C
48 PAGER=cat
49 TZ=UTC
50 TERM=dumb
51 export LANG LC_ALL PAGER TERM TZ
52 GIT_TEST_CMP=${GIT_TEST_CMP:-diff -u}
53
54 # Protect ourselves from common misconfiguration to export
55 # CDPATH into the environment
56 unset CDPATH
57
58 unset GREP_OPTIONS
59
60 # Convenience
61 #
62 # A regexp to match 5 and 40 hexdigits
63 _x05='[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]'
64 _x40="$_x05$_x05$_x05$_x05$_x05$_x05$_x05$_x05"
65
66 _x04='[0-9a-f][0-9a-f][0-9a-f][0-9a-f]'
67 _x32="$_x04$_x04$_x04$_x04$_x04$_x04$_x04$_x04"
68
69 # Each test should start with something like this, after copyright notices:
70 #
71 # test_description='Description of this test...
72 # This test checks if command xyzzy does the right thing...
73 # '
74 # . ./test-lib.sh
75 [ "x$ORIGINAL_TERM" != "xdumb" ] && (
76                 TERM=$ORIGINAL_TERM &&
77                 export TERM &&
78                 [ -t 1 ] &&
79                 tput bold >/dev/null 2>&1 &&
80                 tput setaf 1 >/dev/null 2>&1 &&
81                 tput sgr0 >/dev/null 2>&1
82         ) &&
83         color=t
84
85 while test "$#" -ne 0
86 do
87         case "$1" in
88         -d|--d|--de|--deb|--debu|--debug)
89                 debug=t; shift ;;
90         -i|--i|--im|--imm|--imme|--immed|--immedi|--immedia|--immediat|--immediate)
91                 immediate=t; shift ;;
92         -l|--l|--lo|--lon|--long|--long-|--long-t|--long-te|--long-tes|--long-test|--long-tests)
93                 GIT_TEST_LONG=t; export GIT_TEST_LONG; shift ;;
94         -h|--h|--he|--hel|--help)
95                 help=t; shift ;;
96         -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose)
97                 verbose=t; shift ;;
98         -q|--q|--qu|--qui|--quie|--quiet)
99                 quiet=t; shift ;;
100         --with-dashes)
101                 with_dashes=t; shift ;;
102         --no-color)
103                 color=; shift ;;
104         --no-python)
105                 # noop now...
106                 shift ;;
107         --va|--val|--valg|--valgr|--valgri|--valgrin|--valgrind)
108                 valgrind=t; verbose=t; shift ;;
109         --tee)
110                 shift ;; # was handled already
111         --root=*)
112                 root=$(expr "z$1" : 'z[^=]*=\(.*\)')
113                 shift ;;
114         *)
115                 echo "error: unknown test option '$1'" >&2; exit 1 ;;
116         esac
117 done
118
119 if test -n "$color"; then
120         say_color () {
121                 (
122                 TERM=$ORIGINAL_TERM
123                 export TERM
124                 case "$1" in
125                         error) tput bold; tput setaf 1;; # bold red
126                         skip)  tput bold; tput setaf 2;; # bold green
127                         pass)  tput setaf 2;;            # green
128                         info)  tput setaf 3;;            # brown
129                         *) test -n "$quiet" && return;;
130                 esac
131                 shift
132                 printf " "
133                 printf "$@"
134                 tput sgr0
135                 )
136         }
137 else
138         say_color() {
139                 test -z "$1" && test -n "$quiet" && return
140                 shift
141                 printf " "
142                 printf "$@"
143         }
144 fi
145
146 error () {
147         say_color error "error: $*\n"
148         GIT_EXIT_OK=t
149         exit 1
150 }
151
152 say () {
153         say_color info "$*"
154 }
155
156 test "${test_description}" != "" ||
157 error "Test script did not set test_description."
158
159 if test "$help" = "t"
160 then
161         echo "Tests ${test_description}"
162         exit 0
163 fi
164
165 echo $(basename "$0"): "Testing ${test_description}"
166
167 exec 5>&1
168
169 test_failure=0
170 test_count=0
171 test_fixed=0
172 test_broken=0
173 test_success=0
174
175 die () {
176         code=$?
177         rm -rf "$TEST_TMPDIR"
178         if test -n "$GIT_EXIT_OK"
179         then
180                 exit $code
181         else
182                 echo >&5 "FATAL: Unexpected exit with code $code"
183                 exit 1
184         fi
185 }
186
187 GIT_EXIT_OK=
188 # Note: TEST_TMPDIR *NOT* exported!
189 TEST_TMPDIR=$(mktemp -d "${TMPDIR:-/tmp}/notmuch-test-$$.XXXXXX")
190 trap 'die' EXIT
191
192 test_decode_color () {
193         sed     -e 's/.\[1m/<WHITE>/g' \
194                 -e 's/.\[31m/<RED>/g' \
195                 -e 's/.\[32m/<GREEN>/g' \
196                 -e 's/.\[33m/<YELLOW>/g' \
197                 -e 's/.\[34m/<BLUE>/g' \
198                 -e 's/.\[35m/<MAGENTA>/g' \
199                 -e 's/.\[36m/<CYAN>/g' \
200                 -e 's/.\[m/<RESET>/g'
201 }
202
203 q_to_nul () {
204         perl -pe 'y/Q/\000/'
205 }
206
207 q_to_cr () {
208         tr Q '\015'
209 }
210
211 append_cr () {
212         sed -e 's/$/Q/' | tr Q '\015'
213 }
214
215 remove_cr () {
216         tr '\015' Q | sed -e 's/Q$//'
217 }
218
219 # Generate a new message in the mail directory, with a unique message
220 # ID and subject. The message is not added to the index.
221 #
222 # After this function returns, the filename of the generated message
223 # is available as $gen_msg_filename and the message ID is available as
224 # $gen_msg_id .
225 #
226 # This function supports named parameters with the bash syntax for
227 # assigning a value to an associative array ([name]=value). The
228 # supported parameters are:
229 #
230 #  [dir]=directory/of/choice
231 #
232 #       Generate the message in directory 'directory/of/choice' within
233 #       the mail store. The directory will be created if necessary.
234 #
235 #  [filename]=name
236 #
237 #       Store the message in file 'name'. The default is to store it
238 #       in 'msg-<count>', where <count> is three-digit number of the
239 #       message.
240 #       
241 #  [body]=text
242 #
243 #       Text to use as the body of the email message
244 #
245 #  '[from]="Some User <user@example.com>"'
246 #  '[to]="Some User <user@example.com>"'
247 #  '[subject]="Subject of email message"'
248 #  '[date]="RFC 822 Date"'
249 #
250 #       Values for email headers. If not provided, default values will
251 #       be generated instead.
252 #
253 #  '[cc]="Some User <user@example.com>"'
254 #  [reply-to]=some-address
255 #  [in-reply-to]=<message-id>
256 #  [references]=<message-id>
257 #  [content-type]=content-type-specification
258 #  '[header]=full header line, including keyword'
259 #
260 #       Additional values for email headers. If these are not provided
261 #       then the relevant headers will simply not appear in the
262 #       message.
263 #
264 #  '[id]=message-id'
265 #
266 #       Controls the message-id of the created message.
267 gen_msg_cnt=0
268 gen_msg_filename=""
269 gen_msg_id=""
270 generate_message ()
271 {
272     # This is our (bash-specific) magic for doing named parameters
273     local -A template="($@)"
274     local additional_headers
275
276     gen_msg_cnt=$((gen_msg_cnt + 1))
277     if [ -z "${template[filename]}" ]; then
278         gen_msg_name="msg-$(printf "%03d" $gen_msg_cnt)"
279     else
280         gen_msg_name=${template[filename]}
281     fi
282
283     if [ -z "${template[id]}" ]; then
284         gen_msg_id="${gen_msg_name%:2,*}@notmuch-test-suite"
285     else
286         gen_msg_id="${template[id]}"
287     fi
288
289     if [ -z "${template[dir]}" ]; then
290         gen_msg_filename="${MAIL_DIR}/$gen_msg_name"
291     else
292         gen_msg_filename="${MAIL_DIR}/${template[dir]}/$gen_msg_name"
293         mkdir -p "$(dirname "$gen_msg_filename")"
294     fi
295
296     if [ -z "${template[body]}" ]; then
297         template[body]="This is just a test message (#${gen_msg_cnt})"
298     fi
299
300     if [ -z "${template[from]}" ]; then
301         template[from]="Notmuch Test Suite <test_suite@notmuchmail.org>"
302     fi
303
304     if [ -z "${template[to]}" ]; then
305         template[to]="Notmuch Test Suite <test_suite@notmuchmail.org>"
306     fi
307
308     if [ -z "${template[subject]}" ]; then
309         template[subject]="Test message #${gen_msg_cnt}"
310     fi
311
312     if [ -z "${template[date]}" ]; then
313         template[date]="Tue, 05 Jan 2001 15:43:57 -0000"
314     fi
315
316     additional_headers=""
317     if [ ! -z "${template[header]}" ]; then
318         additional_headers="${template[header]}
319 ${additional_headers}"
320     fi
321
322     if [ ! -z "${template[reply-to]}" ]; then
323         additional_headers="Reply-To: ${template[reply-to]}
324 ${additional_headers}"
325     fi
326
327     if [ ! -z "${template[in-reply-to]}" ]; then
328         additional_headers="In-Reply-To: ${template[in-reply-to]}
329 ${additional_headers}"
330     fi
331
332     if [ ! -z "${template[cc]}" ]; then
333         additional_headers="Cc: ${template[cc]}
334 ${additional_headers}"
335     fi
336
337     if [ ! -z "${template[references]}" ]; then
338         additional_headers="References: ${template[references]}
339 ${additional_headers}"
340     fi
341
342     if [ ! -z "${template[content-type]}" ]; then
343         additional_headers="Content-Type: ${template[content-type]}
344 ${additional_headers}"
345     fi
346
347     # Note that in the way we're setting it above and using it below,
348     # `additional_headers' will also serve as the header / body separator
349     # (empty line in between).
350
351     cat <<EOF >"$gen_msg_filename"
352 From: ${template[from]}
353 To: ${template[to]}
354 Message-Id: <${gen_msg_id}>
355 Subject: ${template[subject]}
356 Date: ${template[date]}
357 ${additional_headers}
358 ${template[body]}
359 EOF
360 }
361
362 # Generate a new message and add it to the database.
363 #
364 # All of the arguments and return values supported by generate_message
365 # are also supported here, so see that function for details.
366 add_message ()
367 {
368     generate_message "$@" &&
369     notmuch new > /dev/null
370 }
371
372 # Deliver a message with emacs and add it to the database
373 #
374 # Uses emacs to generate and deliver a message to the mail store.
375 # Accepts arbitrary extra emacs/elisp functions to modify the message
376 # before sending, which is useful to doing things like attaching files
377 # to the message and encrypting/signing.
378 emacs_deliver_message ()
379 {
380     local subject="$1"
381     local body="$2"
382     shift 2
383     # before we can send a message, we have to prepare the FCC maildir
384     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
385     $TEST_DIRECTORY/smtp-dummy sent_message &
386     smtp_dummy_pid=$!
387     test_emacs \
388         "(let ((message-send-mail-function 'message-smtpmail-send-it)
389                (smtpmail-smtp-server \"localhost\")
390                (smtpmail-smtp-service \"25025\"))
391            (notmuch-hello)
392            (notmuch-mua-mail)
393            (message-goto-to)
394            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
395            (message-goto-subject)
396            (insert \"${subject}\")
397            (message-goto-body)
398            (insert \"${body}\")
399            $@
400            (message-send-and-exit))"
401     wait ${smtp_dummy_pid}
402     notmuch new >/dev/null
403 }
404
405 # Generate a corpus of email and add it to the database.
406 #
407 # This corpus is fixed, (it happens to be 50 messages from early in
408 # the history of the notmuch mailing list), which allows for reliably
409 # testing commands that need to operate on a not-totally-trivial
410 # number of messages.
411 add_email_corpus ()
412 {
413     rm -rf ${MAIL_DIR}
414     if [ -d $TEST_DIRECTORY/corpus.mail ]; then
415         cp -a $TEST_DIRECTORY/corpus.mail ${MAIL_DIR}
416     else
417         cp -a $TEST_DIRECTORY/corpus ${MAIL_DIR}
418         notmuch new >/dev/null
419         cp -a ${MAIL_DIR} $TEST_DIRECTORY/corpus.mail
420     fi
421 }
422
423 test_begin_subtest ()
424 {
425     if [ -n "$inside_subtest" ]; then
426         exec 1>&6 2>&7          # Restore stdout and stderr
427         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
428     fi
429     test_subtest_name="$1"
430     test_subtest_known_broken_=
431     # Remember stdout and stderr file descriptors and redirect test
432     # output to the previously prepared file descriptors 3 and 4 (see
433     # below)
434     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
435     exec 6>&1 7>&2 >&3 2>&4
436     inside_subtest=t
437 }
438
439 # Pass test if two arguments match
440 #
441 # Note: Unlike all other test_expect_* functions, this function does
442 # not accept a test name. Instead, the caller should call
443 # test_begin_subtest before calling this function in order to set the
444 # name.
445 test_expect_equal ()
446 {
447         exec 1>&6 2>&7          # Restore stdout and stderr
448         inside_subtest=
449         test "$#" = 3 && { prereq=$1; shift; } || prereq=
450         test "$#" = 2 ||
451         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
452
453         output="$1"
454         expected="$2"
455         if ! test_skip "$test_subtest_name"
456         then
457                 if [ "$output" = "$expected" ]; then
458                         test_ok_ "$test_subtest_name"
459                 else
460                         testname=$this_test.$test_count
461                         echo "$expected" > $testname.expected
462                         echo "$output" > $testname.output
463                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
464                 fi
465     fi
466 }
467
468 # Like test_expect_equal, but takes two filenames.
469 test_expect_equal_file ()
470 {
471         exec 1>&6 2>&7          # Restore stdout and stderr
472         inside_subtest=
473         test "$#" = 3 && { prereq=$1; shift; } || prereq=
474         test "$#" = 2 ||
475         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
476
477         output="$1"
478         expected="$2"
479         if ! test_skip "$test_subtest_name"
480         then
481                 if diff -q "$expected" "$output" >/dev/null ; then
482                         test_ok_ "$test_subtest_name"
483                 else
484                         testname=$this_test.$test_count
485                         cp "$output" $testname.output
486                         cp "$expected" $testname.expected
487                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
488                 fi
489     fi
490 }
491
492 NOTMUCH_NEW ()
493 {
494     notmuch new | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
495 }
496
497 notmuch_search_sanitize ()
498 {
499     sed -r -e 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
500 }
501
502 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
503 notmuch_show_sanitize ()
504 {
505     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
506 }
507 notmuch_show_sanitize_all ()
508 {
509     sed \
510         -e 's| filename:.*| filename:XXXXX|' \
511         -e 's| id:[^ ]* | id:XXXXX |'
512 }
513
514 notmuch_json_show_sanitize ()
515 {
516     sed -e 's|, |,\n |g' | \
517         sed \
518         -e 's|"id": "[^"]*",|"id": "XXXXX",|' \
519         -e 's|"filename": "[^"]*",|"filename": "YYYYY",|'
520 }
521
522 # End of notmuch helper functions
523
524 # Use test_set_prereq to tell that a particular prerequisite is available.
525 # The prerequisite can later be checked for in two ways:
526 #
527 # - Explicitly using test_have_prereq.
528 #
529 # - Implicitly by specifying the prerequisite tag in the calls to
530 #   test_expect_{success,failure,code}.
531 #
532 # The single parameter is the prerequisite tag (a simple word, in all
533 # capital letters by convention).
534
535 test_set_prereq () {
536         satisfied="$satisfied$1 "
537 }
538 satisfied=" "
539
540 test_have_prereq () {
541         case $satisfied in
542         *" $1 "*)
543                 : yes, have it ;;
544         *)
545                 ! : nope ;;
546         esac
547 }
548
549 # You are not expected to call test_ok_ and test_failure_ directly, use
550 # the text_expect_* functions instead.
551
552 test_ok_ () {
553         if test "$test_subtest_known_broken_" = "t"; then
554                 test_known_broken_ok_ "$@"
555                 return
556         fi
557         test_success=$(($test_success + 1))
558         say_color pass "%-6s" "PASS"
559         echo " $@"
560 }
561
562 test_failure_ () {
563         if test "$test_subtest_known_broken_" = "t"; then
564                 test_known_broken_failure_ "$@"
565                 return
566         fi
567         test_failure=$(($test_failure + 1))
568         test_failure_message_ "FAIL" "$@"
569         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
570         return 1
571 }
572
573 test_failure_message_ () {
574         say_color error "%-6s" "$1"
575         echo " $2"
576         shift 2
577         echo "$@" | sed -e 's/^/        /'
578         if test "$verbose" != "t"; then cat test.output; fi
579 }
580
581 test_known_broken_ok_ () {
582         test_subtest_known_broken_=
583         test_fixed=$(($test_fixed+1))
584         say_color pass "%-6s" "FIXED"
585         echo " $@"
586 }
587
588 test_known_broken_failure_ () {
589         test_subtest_known_broken_=
590         test_broken=$(($test_broken+1))
591         test_failure_message_ "BROKEN" "$@"
592         return 1
593 }
594
595 test_debug () {
596         test "$debug" = "" || eval "$1"
597 }
598
599 test_run_ () {
600         test_cleanup=:
601         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
602         eval >&3 2>&4 "$1"
603         eval_ret=$?
604         eval >&3 2>&4 "$test_cleanup"
605         return 0
606 }
607
608 test_skip () {
609         test_count=$(($test_count+1))
610         to_skip=
611         for skp in $NOTMUCH_SKIP_TESTS
612         do
613                 case $this_test.$test_count in
614                 $skp)
615                         to_skip=t
616                 esac
617         done
618         if test -z "$to_skip" && test -n "$prereq" &&
619            ! test_have_prereq "$prereq"
620         then
621                 to_skip=t
622         fi
623         case "$to_skip" in
624         t)
625                 test_subtest_known_broken_=
626                 say_color skip >&3 "skipping test: $@"
627                 say_color skip "%-6s" "SKIP"
628                 echo " $1"
629                 : true
630                 ;;
631         *)
632                 false
633                 ;;
634         esac
635 }
636
637 test_subtest_known_broken () {
638         test_subtest_known_broken_=t
639 }
640
641 test_expect_success () {
642         test "$#" = 3 && { prereq=$1; shift; } || prereq=
643         test "$#" = 2 ||
644         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
645         if ! test_skip "$@"
646         then
647                 test_run_ "$2"
648                 if [ "$?" = 0 -a "$eval_ret" = 0 ]
649                 then
650                         test_ok_ "$1"
651                 else
652                         test_failure_ "$@"
653                 fi
654         fi
655 }
656
657 test_expect_code () {
658         test "$#" = 4 && { prereq=$1; shift; } || prereq=
659         test "$#" = 3 ||
660         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
661         if ! test_skip "$@"
662         then
663                 test_run_ "$3"
664                 if [ "$?" = 0 -a "$eval_ret" = "$1" ]
665                 then
666                         test_ok_ "$2"
667                 else
668                         test_failure_ "$@"
669                 fi
670         fi
671 }
672
673 # test_external runs external test scripts that provide continuous
674 # test output about their progress, and succeeds/fails on
675 # zero/non-zero exit code.  It outputs the test output on stdout even
676 # in non-verbose mode, and announces the external script with "* run
677 # <n>: ..." before running it.  When providing relative paths, keep in
678 # mind that all scripts run in "trash directory".
679 # Usage: test_external description command arguments...
680 # Example: test_external 'Perl API' perl ../path/to/test.pl
681 test_external () {
682         test "$#" = 4 && { prereq=$1; shift; } || prereq=
683         test "$#" = 3 ||
684         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
685         descr="$1"
686         shift
687         if ! test_skip "$descr" "$@"
688         then
689                 # Announce the script to reduce confusion about the
690                 # test output that follows.
691                 say_color "" " run $test_count: $descr ($*)"
692                 # Run command; redirect its stderr to &4 as in
693                 # test_run_, but keep its stdout on our stdout even in
694                 # non-verbose mode.
695                 "$@" 2>&4
696                 if [ "$?" = 0 ]
697                 then
698                         test_ok_ "$descr"
699                 else
700                         test_failure_ "$descr" "$@"
701                 fi
702         fi
703 }
704
705 # Like test_external, but in addition tests that the command generated
706 # no output on stderr.
707 test_external_without_stderr () {
708         # The temporary file has no (and must have no) security
709         # implications.
710         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
711         stderr="$tmp/git-external-stderr.$$.tmp"
712         test_external "$@" 4> "$stderr"
713         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
714         descr="no stderr: $1"
715         shift
716         if [ ! -s "$stderr" ]; then
717                 rm "$stderr"
718                 test_ok_ "$descr"
719         else
720                 if [ "$verbose" = t ]; then
721                         output=`echo; echo Stderr is:; cat "$stderr"`
722                 else
723                         output=
724                 fi
725                 # rm first in case test_failure exits.
726                 rm "$stderr"
727                 test_failure_ "$descr" "$@" "$output"
728         fi
729 }
730
731 # This is not among top-level (test_expect_success)
732 # but is a prefix that can be used in the test script, like:
733 #
734 #       test_expect_success 'complain and die' '
735 #           do something &&
736 #           do something else &&
737 #           test_must_fail git checkout ../outerspace
738 #       '
739 #
740 # Writing this as "! git checkout ../outerspace" is wrong, because
741 # the failure could be due to a segv.  We want a controlled failure.
742
743 test_must_fail () {
744         "$@"
745         test $? -gt 0 -a $? -le 129 -o $? -gt 192
746 }
747
748 # test_cmp is a helper function to compare actual and expected output.
749 # You can use it like:
750 #
751 #       test_expect_success 'foo works' '
752 #               echo expected >expected &&
753 #               foo >actual &&
754 #               test_cmp expected actual
755 #       '
756 #
757 # This could be written as either "cmp" or "diff -u", but:
758 # - cmp's output is not nearly as easy to read as diff -u
759 # - not all diff versions understand "-u"
760
761 test_cmp() {
762         $GIT_TEST_CMP "$@"
763 }
764
765 # This function can be used to schedule some commands to be run
766 # unconditionally at the end of the test to restore sanity:
767 #
768 #       test_expect_success 'test core.capslock' '
769 #               git config core.capslock true &&
770 #               test_when_finished "git config --unset core.capslock" &&
771 #               hello world
772 #       '
773 #
774 # That would be roughly equivalent to
775 #
776 #       test_expect_success 'test core.capslock' '
777 #               git config core.capslock true &&
778 #               hello world
779 #               git config --unset core.capslock
780 #       '
781 #
782 # except that the greeting and config --unset must both succeed for
783 # the test to pass.
784
785 test_when_finished () {
786         test_cleanup="{ $*
787                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
788 }
789
790 test_done () {
791         GIT_EXIT_OK=t
792         test_results_dir="$TEST_DIRECTORY/test-results"
793         mkdir -p "$test_results_dir"
794         test_results_path="$test_results_dir/${0%.sh}-$$"
795
796         echo "total $test_count" >> $test_results_path
797         echo "success $test_success" >> $test_results_path
798         echo "fixed $test_fixed" >> $test_results_path
799         echo "broken $test_broken" >> $test_results_path
800         echo "failed $test_failure" >> $test_results_path
801         echo "" >> $test_results_path
802
803         echo
804
805         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
806
807         if [ "$test_failure" = "0" ]; then
808             if [ "$test_broken" = "0" ]; then       
809                 rm -rf "$remove_tmp"
810             fi
811             exit 0
812         else
813             exit 1
814         fi
815 }
816
817 emacs_generate_script () {
818         # Construct a little test script here for the benefit of the user,
819         # (who can easily run "run_emacs" to get the same emacs environment
820         # for investigating any failures).    
821         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
822 #!/bin/sh
823 export PATH=$PATH
824 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
825
826 # Here's what we are using here:
827 #
828 # --no-init-file        Don't load users ~/.emacs
829 #
830 # --no-site-file        Don't load the site-wide startup stuff
831 #
832 # --directory           Ensure that the local elisp sources are found
833 #
834 # --load                Force loading of notmuch.el and test-lib.el
835
836 exec emacs --no-init-file --no-site-file \
837         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
838         --directory "$TEST_DIRECTORY" --load test-lib.el \
839         "\$@"
840 EOF
841         chmod a+x "$TMP_DIRECTORY/run_emacs"
842 }
843
844 test_emacs () {
845         if [ -z "$EMACS_SERVER" ]; then
846                 EMACS_SERVER="notmuch-test-suite-$$"
847                 # start a detached session with an emacs server
848                 # user's TERM is given to dtach which assumes a minimally
849                 # VT100-compatible terminal -- and emacs inherits that
850                 TERM=$ORIGINAL_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
851                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
852                                 --no-window-system \
853                                 --eval '(setq server-name \"$EMACS_SERVER\")' \
854                                 --eval '(server-start)' \
855                                 --eval '(orphan-watchdog $$)'" || return
856                 # wait until the emacs server is up
857                 until test_emacs '()' 2>/dev/null; do
858                         sleep 1
859                 done
860         fi
861
862         emacsclient --socket-name="$EMACS_SERVER" --eval "(progn $@)"
863 }
864
865
866 find_notmuch_path ()
867 {
868     dir="$1"
869
870     while [ -n "$dir" ]; do
871         bin="$dir/notmuch"
872         if [ -x "$bin" ]; then
873             echo "$dir"
874             return
875         fi
876         dir="$(dirname "$dir")"
877         if [ "$dir" = "/" ]; then
878             break
879         fi
880     done
881 }
882
883 # Test the binaries we have just built.  The tests are kept in
884 # test/ subdirectory and are run in 'trash directory' subdirectory.
885 TEST_DIRECTORY=$(pwd)
886 if test -n "$valgrind"
887 then
888         make_symlink () {
889                 test -h "$2" &&
890                 test "$1" = "$(readlink "$2")" || {
891                         # be super paranoid
892                         if mkdir "$2".lock
893                         then
894                                 rm -f "$2" &&
895                                 ln -s "$1" "$2" &&
896                                 rm -r "$2".lock
897                         else
898                                 while test -d "$2".lock
899                                 do
900                                         say "Waiting for lock on $2."
901                                         sleep 1
902                                 done
903                         fi
904                 }
905         }
906
907         make_valgrind_symlink () {
908                 # handle only executables
909                 test -x "$1" || return
910
911                 base=$(basename "$1")
912                 symlink_target=$TEST_DIRECTORY/../$base
913                 # do not override scripts
914                 if test -x "$symlink_target" &&
915                     test ! -d "$symlink_target" &&
916                     test "#!" != "$(head -c 2 < "$symlink_target")"
917                 then
918                         symlink_target=$TEST_DIRECTORY/valgrind.sh
919                 fi
920                 case "$base" in
921                 *.sh|*.perl)
922                         symlink_target=$TEST_DIRECTORY/unprocessed-script
923                 esac
924                 # create the link, or replace it if it is out of date
925                 make_symlink "$symlink_target" "$GIT_VALGRIND/bin/$base" || exit
926         }
927
928         # override notmuch executable in TEST_DIRECTORY/..
929         GIT_VALGRIND=$TEST_DIRECTORY/valgrind
930         mkdir -p "$GIT_VALGRIND"/bin
931         make_valgrind_symlink $TEST_DIRECTORY/../notmuch
932         OLDIFS=$IFS
933         IFS=:
934         for path in $PATH
935         do
936                 ls "$path"/notmuch 2> /dev/null |
937                 while read file
938                 do
939                         make_valgrind_symlink "$file"
940                 done
941         done
942         IFS=$OLDIFS
943         PATH=$GIT_VALGRIND/bin:$PATH
944         GIT_EXEC_PATH=$GIT_VALGRIND/bin
945         export GIT_VALGRIND
946 else # normal case
947         notmuch_path=`find_notmuch_path "$TEST_DIRECTORY"`
948         test -n "$notmuch_path" && PATH="$notmuch_path:$PATH"
949 fi
950 export PATH
951
952 # Test repository
953 test="tmp.$(basename "$0" .sh)"
954 test -n "$root" && test="$root/$test"
955 case "$test" in
956 /*) TMP_DIRECTORY="$test" ;;
957  *) TMP_DIRECTORY="$TEST_DIRECTORY/$test" ;;
958 esac
959 test ! -z "$debug" || remove_tmp=$TMP_DIRECTORY
960 rm -fr "$test" || {
961         GIT_EXIT_OK=t
962         echo >&5 "FATAL: Cannot prepare test area"
963         exit 1
964 }
965
966 # A temporary home directory is needed by at least:
967 # - emacs/"Sending a message via (fake) SMTP"
968 # - emacs/"Reply within emacs"
969 # - crypto/emacs_deliver_message
970 export HOME="${TMP_DIRECTORY}/home"
971 mkdir -p "${HOME}"
972
973 MAIL_DIR="${TMP_DIRECTORY}/mail"
974 export GNUPGHOME="${TMP_DIRECTORY}/gnupg"
975 export NOTMUCH_CONFIG="${TMP_DIRECTORY}/notmuch-config"
976
977 mkdir -p "${test}"
978 mkdir -p "${MAIL_DIR}"
979
980 cat <<EOF >"${NOTMUCH_CONFIG}"
981 [database]
982 path=${MAIL_DIR}
983
984 [user]
985 name=Notmuch Test Suite
986 primary_email=test_suite@notmuchmail.org
987 other_email=test_suite_other@notmuchmail.org;test_suite@otherdomain.org
988 EOF
989
990 emacs_generate_script
991
992
993 # Use -P to resolve symlinks in our working directory so that the cwd
994 # in subprocesses like git equals our $PWD (for pathname comparisons).
995 cd -P "$test" || error "Cannot setup test environment"
996
997 if test "$verbose" = "t"
998 then
999         exec 4>&2 3>&1
1000 else
1001         exec 4>test.output 3>&4
1002 fi
1003
1004 this_test=${0##*/}
1005 for skp in $NOTMUCH_SKIP_TESTS
1006 do
1007         to_skip=
1008         for skp in $NOTMUCH_SKIP_TESTS
1009         do
1010                 case "$this_test" in
1011                 $skp)
1012                         to_skip=t
1013                 esac
1014         done
1015         case "$to_skip" in
1016         t)
1017                 say_color skip >&3 "skipping test $this_test altogether"
1018                 say_color skip "skip all tests in $this_test"
1019                 test_done
1020         esac
1021 done
1022
1023 # Provide an implementation of the 'yes' utility
1024 yes () {
1025         if test $# = 0
1026         then
1027                 y=y
1028         else
1029                 y="$*"
1030         fi
1031
1032         while echo "$y"
1033         do
1034                 :
1035         done
1036 }
1037
1038 # Fix some commands on Windows
1039 case $(uname -s) in
1040 *MINGW*)
1041         # Windows has its own (incompatible) sort and find
1042         sort () {
1043                 /usr/bin/sort "$@"
1044         }
1045         find () {
1046                 /usr/bin/find "$@"
1047         }
1048         sum () {
1049                 md5sum "$@"
1050         }
1051         # git sees Windows-style pwd
1052         pwd () {
1053                 builtin pwd -W
1054         }
1055         # no POSIX permissions
1056         # backslashes in pathspec are converted to '/'
1057         # exec does not inherit the PID
1058         ;;
1059 *)
1060         test_set_prereq POSIXPERM
1061         test_set_prereq BSLASHPSPEC
1062         test_set_prereq EXECKEEPSPID
1063         ;;
1064 esac
1065
1066 test -z "$NO_PERL" && test_set_prereq PERL
1067 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1068
1069 # test whether the filesystem supports symbolic links
1070 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1071 rm -f y