]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: new test-lib function to test for equality between files
[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
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         if test -n "$GIT_EXIT_OK"
178         then
179                 exit $code
180         else
181                 echo >&5 "FATAL: Unexpected exit with code $code"
182                 exit 1
183         fi
184 }
185
186 GIT_EXIT_OK=
187 trap 'die' EXIT
188
189 test_decode_color () {
190         sed     -e 's/.\[1m/<WHITE>/g' \
191                 -e 's/.\[31m/<RED>/g' \
192                 -e 's/.\[32m/<GREEN>/g' \
193                 -e 's/.\[33m/<YELLOW>/g' \
194                 -e 's/.\[34m/<BLUE>/g' \
195                 -e 's/.\[35m/<MAGENTA>/g' \
196                 -e 's/.\[36m/<CYAN>/g' \
197                 -e 's/.\[m/<RESET>/g'
198 }
199
200 q_to_nul () {
201         perl -pe 'y/Q/\000/'
202 }
203
204 q_to_cr () {
205         tr Q '\015'
206 }
207
208 append_cr () {
209         sed -e 's/$/Q/' | tr Q '\015'
210 }
211
212 remove_cr () {
213         tr '\015' Q | sed -e 's/Q$//'
214 }
215
216 # Notmuch helper functions
217 increment_mtime_amount=0
218 increment_mtime ()
219 {
220     dir="$1"
221
222     increment_mtime_amount=$((increment_mtime_amount + 1))
223     touch -d "+${increment_mtime_amount} seconds" "$dir"
224 }
225
226 # Generate a new message in the mail directory, with a unique message
227 # ID and subject. The message is not added to the index.
228 #
229 # After this function returns, the filename of the generated message
230 # is available as $gen_msg_filename and the message ID is available as
231 # $gen_msg_id .
232 #
233 # This function supports named parameters with the bash syntax for
234 # assigning a value to an associative array ([name]=value). The
235 # supported parameters are:
236 #
237 #  [dir]=directory/of/choice
238 #
239 #       Generate the message in directory 'directory/of/choice' within
240 #       the mail store. The directory will be created if necessary.
241 #
242 #  [filename]=name
243 #
244 #       Store the message in file 'name'. The default is to store it
245 #       in 'msg-<count>', where <count> is three-digit number of the
246 #       message.
247 #       
248 #  [body]=text
249 #
250 #       Text to use as the body of the email message
251 #
252 #  '[from]="Some User <user@example.com>"'
253 #  '[to]="Some User <user@example.com>"'
254 #  '[subject]="Subject of email message"'
255 #  '[date]="RFC 822 Date"'
256 #
257 #       Values for email headers. If not provided, default values will
258 #       be generated instead.
259 #
260 #  '[cc]="Some User <user@example.com>"'
261 #  [reply-to]=some-address
262 #  [in-reply-to]=<message-id>
263 #  [references]=<message-id>
264 #  [content-type]=content-type-specification
265 #  '[header]=full header line, including keyword'
266 #
267 #       Additional values for email headers. If these are not provided
268 #       then the relevant headers will simply not appear in the
269 #       message.
270 #
271 #  '[id]=message-id'
272 #
273 #       Controls the message-id of the created message.
274 gen_msg_cnt=0
275 gen_msg_filename=""
276 gen_msg_id=""
277 generate_message ()
278 {
279     # This is our (bash-specific) magic for doing named parameters
280     local -A template="($@)"
281     local additional_headers
282
283     gen_msg_cnt=$((gen_msg_cnt + 1))
284     if [ -z "${template[filename]}" ]; then
285         gen_msg_name="msg-$(printf "%03d" $gen_msg_cnt)"
286     else
287         gen_msg_name=${template[filename]}
288     fi
289
290     if [ -z "${template[id]}" ]; then
291         gen_msg_id="${gen_msg_name%:2,*}@notmuch-test-suite"
292     else
293         gen_msg_id="${template[id]}"
294     fi
295
296     if [ -z "${template[dir]}" ]; then
297         gen_msg_filename="${MAIL_DIR}/$gen_msg_name"
298     else
299         gen_msg_filename="${MAIL_DIR}/${template[dir]}/$gen_msg_name"
300         mkdir -p "$(dirname "$gen_msg_filename")"
301     fi
302
303     if [ -z "${template[body]}" ]; then
304         template[body]="This is just a test message (#${gen_msg_cnt})"
305     fi
306
307     if [ -z "${template[from]}" ]; then
308         template[from]="Notmuch Test Suite <test_suite@notmuchmail.org>"
309     fi
310
311     if [ -z "${template[to]}" ]; then
312         template[to]="Notmuch Test Suite <test_suite@notmuchmail.org>"
313     fi
314
315     if [ -z "${template[subject]}" ]; then
316         template[subject]="Test message #${gen_msg_cnt}"
317     fi
318
319     if [ -z "${template[date]}" ]; then
320         template[date]="Tue, 05 Jan 2001 15:43:57 -0000"
321     fi
322
323     additional_headers=""
324     if [ ! -z "${template[header]}" ]; then
325         additional_headers="${template[header]}
326 ${additional_headers}"
327     fi
328
329     if [ ! -z "${template[reply-to]}" ]; then
330         additional_headers="Reply-To: ${template[reply-to]}
331 ${additional_headers}"
332     fi
333
334     if [ ! -z "${template[in-reply-to]}" ]; then
335         additional_headers="In-Reply-To: ${template[in-reply-to]}
336 ${additional_headers}"
337     fi
338
339     if [ ! -z "${template[cc]}" ]; then
340         additional_headers="Cc: ${template[cc]}
341 ${additional_headers}"
342     fi
343
344     if [ ! -z "${template[references]}" ]; then
345         additional_headers="References: ${template[references]}
346 ${additional_headers}"
347     fi
348
349     if [ ! -z "${template[content-type]}" ]; then
350         additional_headers="Content-Type: ${template[content-type]}
351 ${additional_headers}"
352     fi
353
354     # Note that in the way we're setting it above and using it below,
355     # `additional_headers' will also serve as the header / body separator
356     # (empty line in between).
357
358     cat <<EOF >"$gen_msg_filename"
359 From: ${template[from]}
360 To: ${template[to]}
361 Message-Id: <${gen_msg_id}>
362 Subject: ${template[subject]}
363 Date: ${template[date]}
364 ${additional_headers}
365 ${template[body]}
366 EOF
367
368     # Ensure that the mtime of the containing directory is updated
369     increment_mtime "$(dirname "${gen_msg_filename}")"
370 }
371
372 # Generate a new message and add it to the database.
373 #
374 # All of the arguments and return values supported by generate_message
375 # are also supported here, so see that function for details.
376 add_message ()
377 {
378     generate_message "$@" &&
379     notmuch new > /dev/null
380 }
381
382 # Generate a corpus of email and add it to the database.
383 #
384 # This corpus is fixed, (it happens to be 50 messages from early in
385 # the history of the notmuch mailing list), which allows for reliably
386 # testing commands that need to operate on a not-totally-trivial
387 # number of messages.
388 add_email_corpus ()
389 {
390     rm -rf ${MAIL_DIR}
391     if [ -d ../corpus.mail ]; then
392         cp -a ../corpus.mail ${MAIL_DIR}
393     else
394         cp -a ../corpus ${MAIL_DIR}
395         notmuch new >/dev/null
396         cp -a ${MAIL_DIR} ../corpus.mail
397     fi
398 }
399
400 test_begin_subtest ()
401 {
402     if [ -n "$inside_subtest" ]; then
403         exec 1>&6 2>&7          # Restore stdout and stderr
404         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
405     fi
406     test_subtest_name="$1"
407     # Remember stdout and stderr file descriptios and redirect test
408     # output to the previously prepared file descriptors 3 and 4 (see
409     # below)
410     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
411     exec 6>&1 7>&2 >&3 2>&4
412     inside_subtest=t
413 }
414
415 # Pass test if two arguments match
416 #
417 # Note: Unlike all other test_expect_* functions, this function does
418 # not accept a test name. Instead, the caller should call
419 # test_begin_subtest before calling this function in order to set the
420 # name.
421 test_expect_equal ()
422 {
423         exec 1>&6 2>&7          # Restore stdout and stderr
424         inside_subtest=
425         test "$#" = 3 && { prereq=$1; shift; } || prereq=
426         test "$#" = 2 ||
427         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
428
429         output="$1"
430         expected="$2"
431         if ! test_skip "$@"
432         then
433                 if [ "$output" = "$expected" ]; then
434                         test_ok_ "$test_subtest_name"
435                 else
436                         testname=$this_test.$test_count
437                         echo "$expected" > $testname.expected
438                         echo "$output" > $testname.output
439                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
440                 fi
441     fi
442 }
443
444 test_expect_equal_file ()
445 {
446         exec 1>&6 2>&7          # Restore stdout and stderr
447         inside_subtest=
448         test "$#" = 3 && { prereq=$1; shift; } || prereq=
449         test "$#" = 2 ||
450         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
451
452         output="$1"
453         expected="$2"
454         if ! test_skip "$@"
455         then
456                 if diff -q "$expected" "$output" >/dev/null ; then
457                         test_ok_ "$test_subtest_name"
458                 else
459                         testname=$this_test.$test_count
460                         mv "$output" $testname.output
461                         mv "$expected" $testname.expected
462                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
463                 fi
464     fi
465 }
466
467 test_expect_equal_failure ()
468 {
469         exec 1>&6 2>&7          # Restore stdout and stderr
470         inside_subtest=
471         test "$#" = 3 && { prereq=$1; shift; } || prereq=
472         test "$#" = 2 ||
473         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
474
475         output="$1"
476         expected="$2"
477         if ! test_skip "$@"
478         then
479                 if [ "$output" = "$expected" ]; then
480                         test_known_broken_ok_ "$test_subtest_name"
481                 else
482                         test_known_broken_failure_ "$test_subtest_name"
483                         testname=$this_test.$test_count
484                         echo "$expected" > $testname.expected
485                         echo "$output" > $testname.output
486                 fi
487     fi
488 }
489
490 NOTMUCH_NEW ()
491 {
492     notmuch new | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
493 }
494
495 notmuch_search_sanitize ()
496 {
497     sed -r -e 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
498 }
499
500 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
501 notmuch_show_sanitize ()
502 {
503     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
504 }
505
506 # End of notmuch helper functions
507
508 # Use test_set_prereq to tell that a particular prerequisite is available.
509 # The prerequisite can later be checked for in two ways:
510 #
511 # - Explicitly using test_have_prereq.
512 #
513 # - Implicitly by specifying the prerequisite tag in the calls to
514 #   test_expect_{success,failure,code}.
515 #
516 # The single parameter is the prerequisite tag (a simple word, in all
517 # capital letters by convention).
518
519 test_set_prereq () {
520         satisfied="$satisfied$1 "
521 }
522 satisfied=" "
523
524 test_have_prereq () {
525         case $satisfied in
526         *" $1 "*)
527                 : yes, have it ;;
528         *)
529                 ! : nope ;;
530         esac
531 }
532
533 # You are not expected to call test_ok_ and test_failure_ directly, use
534 # the text_expect_* functions instead.
535
536 test_ok_ () {
537         test_success=$(($test_success + 1))
538         say_color pass "%-6s" "PASS"
539         echo " $@"
540 }
541
542 test_failure_ () {
543         test_failure=$(($test_failure + 1))
544         say_color error "%-6s" "FAIL"
545         echo " $1"
546         shift
547         echo "$@" | sed -e 's/^/        /'
548         if test "$verbose" != "t"; then cat test.output; fi
549         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
550 }
551
552 test_known_broken_ok_ () {
553         test_fixed=$(($test_fixed+1))
554         say_color pass "%-6s" "FIXED"
555         echo " $@"
556 }
557
558 test_known_broken_failure_ () {
559         test_broken=$(($test_broken+1))
560         say_color pass "%-6s" "BROKEN"
561         echo " $@"
562 }
563
564 test_debug () {
565         test "$debug" = "" || eval "$1"
566 }
567
568 test_run_ () {
569         test_cleanup=:
570         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
571         eval >&3 2>&4 "$1"
572         eval_ret=$?
573         eval >&3 2>&4 "$test_cleanup"
574         return 0
575 }
576
577 test_skip () {
578         test_count=$(($test_count+1))
579         to_skip=
580         for skp in $NOTMUCH_SKIP_TESTS
581         do
582                 case $this_test.$test_count in
583                 $skp)
584                         to_skip=t
585                 esac
586         done
587         if test -z "$to_skip" && test -n "$prereq" &&
588            ! test_have_prereq "$prereq"
589         then
590                 to_skip=t
591         fi
592         case "$to_skip" in
593         t)
594                 say_color skip >&3 "skipping test: $@"
595                 say_color skip "%-6s" "SKIP"
596                 echo " $1"
597                 : true
598                 ;;
599         *)
600                 false
601                 ;;
602         esac
603 }
604
605 test_expect_failure () {
606         test "$#" = 3 && { prereq=$1; shift; } || prereq=
607         test "$#" = 2 ||
608         error "bug in the test script: not 2 or 3 parameters to test-expect-failure"
609         if ! test_skip "$@"
610         then
611                 test_run_ "$2"
612                 if [ "$?" = 0 -a "$eval_ret" = 0 ]
613                 then
614                         test_known_broken_ok_ "$1"
615                 else
616                         test_known_broken_failure_ "$1"
617                 fi
618         fi
619 }
620
621 test_expect_success () {
622         test "$#" = 3 && { prereq=$1; shift; } || prereq=
623         test "$#" = 2 ||
624         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
625         if ! test_skip "$@"
626         then
627                 test_run_ "$2"
628                 if [ "$?" = 0 -a "$eval_ret" = 0 ]
629                 then
630                         test_ok_ "$1"
631                 else
632                         test_failure_ "$@"
633                 fi
634         fi
635 }
636
637 test_expect_code () {
638         test "$#" = 4 && { prereq=$1; shift; } || prereq=
639         test "$#" = 3 ||
640         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
641         if ! test_skip "$@"
642         then
643                 test_run_ "$3"
644                 if [ "$?" = 0 -a "$eval_ret" = "$1" ]
645                 then
646                         test_ok_ "$2"
647                 else
648                         test_failure_ "$@"
649                 fi
650         fi
651 }
652
653 # test_external runs external test scripts that provide continuous
654 # test output about their progress, and succeeds/fails on
655 # zero/non-zero exit code.  It outputs the test output on stdout even
656 # in non-verbose mode, and announces the external script with "* run
657 # <n>: ..." before running it.  When providing relative paths, keep in
658 # mind that all scripts run in "trash directory".
659 # Usage: test_external description command arguments...
660 # Example: test_external 'Perl API' perl ../path/to/test.pl
661 test_external () {
662         test "$#" = 4 && { prereq=$1; shift; } || prereq=
663         test "$#" = 3 ||
664         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
665         descr="$1"
666         shift
667         if ! test_skip "$descr" "$@"
668         then
669                 # Announce the script to reduce confusion about the
670                 # test output that follows.
671                 say_color "" " run $test_count: $descr ($*)"
672                 # Run command; redirect its stderr to &4 as in
673                 # test_run_, but keep its stdout on our stdout even in
674                 # non-verbose mode.
675                 "$@" 2>&4
676                 if [ "$?" = 0 ]
677                 then
678                         test_ok_ "$descr"
679                 else
680                         test_failure_ "$descr" "$@"
681                 fi
682         fi
683 }
684
685 # Like test_external, but in addition tests that the command generated
686 # no output on stderr.
687 test_external_without_stderr () {
688         # The temporary file has no (and must have no) security
689         # implications.
690         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
691         stderr="$tmp/git-external-stderr.$$.tmp"
692         test_external "$@" 4> "$stderr"
693         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
694         descr="no stderr: $1"
695         shift
696         if [ ! -s "$stderr" ]; then
697                 rm "$stderr"
698                 test_ok_ "$descr"
699         else
700                 if [ "$verbose" = t ]; then
701                         output=`echo; echo Stderr is:; cat "$stderr"`
702                 else
703                         output=
704                 fi
705                 # rm first in case test_failure exits.
706                 rm "$stderr"
707                 test_failure_ "$descr" "$@" "$output"
708         fi
709 }
710
711 # This is not among top-level (test_expect_success | test_expect_failure)
712 # but is a prefix that can be used in the test script, like:
713 #
714 #       test_expect_success 'complain and die' '
715 #           do something &&
716 #           do something else &&
717 #           test_must_fail git checkout ../outerspace
718 #       '
719 #
720 # Writing this as "! git checkout ../outerspace" is wrong, because
721 # the failure could be due to a segv.  We want a controlled failure.
722
723 test_must_fail () {
724         "$@"
725         test $? -gt 0 -a $? -le 129 -o $? -gt 192
726 }
727
728 # test_cmp is a helper function to compare actual and expected output.
729 # You can use it like:
730 #
731 #       test_expect_success 'foo works' '
732 #               echo expected >expected &&
733 #               foo >actual &&
734 #               test_cmp expected actual
735 #       '
736 #
737 # This could be written as either "cmp" or "diff -u", but:
738 # - cmp's output is not nearly as easy to read as diff -u
739 # - not all diff versions understand "-u"
740
741 test_cmp() {
742         $GIT_TEST_CMP "$@"
743 }
744
745 # This function can be used to schedule some commands to be run
746 # unconditionally at the end of the test to restore sanity:
747 #
748 #       test_expect_success 'test core.capslock' '
749 #               git config core.capslock true &&
750 #               test_when_finished "git config --unset core.capslock" &&
751 #               hello world
752 #       '
753 #
754 # That would be roughly equivalent to
755 #
756 #       test_expect_success 'test core.capslock' '
757 #               git config core.capslock true &&
758 #               hello world
759 #               git config --unset core.capslock
760 #       '
761 #
762 # except that the greeting and config --unset must both succeed for
763 # the test to pass.
764
765 test_when_finished () {
766         test_cleanup="{ $*
767                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
768 }
769
770 test_done () {
771         GIT_EXIT_OK=t
772         test_results_dir="$TEST_DIRECTORY/test-results"
773         mkdir -p "$test_results_dir"
774         test_results_path="$test_results_dir/${0%.sh}-$$"
775
776         echo "total $test_count" >> $test_results_path
777         echo "success $test_success" >> $test_results_path
778         echo "fixed $test_fixed" >> $test_results_path
779         echo "broken $test_broken" >> $test_results_path
780         echo "failed $test_failure" >> $test_results_path
781         echo "" >> $test_results_path
782
783         echo
784
785         if [ "$test_failure" = "0" ]; then
786             if [ "$test_broken" = "0" ]; then       
787                 rm -rf "$remove_tmp"
788             fi
789             exit 0
790         else
791             exit 1
792         fi
793 }
794
795 test_emacs () {
796         # Construct a little test script here for the benefit of the user,
797         # (who can easily run "run_emacs" to get the same emacs environment
798         # for investigating any failures).    
799         cat <<EOF > run_emacs
800 #!/bin/sh
801 export PATH=$PATH
802 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
803
804 # We assume that the user will give a command-line argument only if
805 # wanting to run in batch mode.
806 if [ \$# -gt 0 ]; then
807         BATCH=--batch
808 fi
809
810 # Here's what we are using here:
811 #
812 # --batch:              Quit after given commands and print all (messages)
813 #
814 # --no-init-file        Don't load users ~/.emacs
815 #
816 # --no-site-file        Don't load the site-wide startup stuff
817 #
818 # --directory           Ensure that the local elisp sources are found
819 #
820 # --load                Force loading of notmuch.el and test-lib.el
821 #
822 # notmuch-test-wait     Function for tests to use to wait for process completion
823 #
824 # message-signature     Avoiding appending user's signature on messages
825 #
826 # set-frame-width       80 columns (avoids crazy 10-column default of --batch)
827
828 emacs \$BATCH --no-init-file --no-site-file \
829         --directory ../../emacs --load notmuch.el \
830         --directory .. --load test-lib.el \
831         --eval "(defun notmuch-test-wait ()
832                         (while (get-buffer-process (current-buffer))
833                                 (sleep-for 0.1)))" \
834         --eval "(setq message-signature nil)" \
835         --eval "(progn (set-frame-width (window-frame (get-buffer-window)) 80) \$@)"
836 EOF
837         chmod a+x ./run_emacs
838         ./run_emacs "$@"
839 }
840
841
842 find_notmuch_path ()
843 {
844     dir="$1"
845
846     while [ -n "$dir" ]; do
847         bin="$dir/notmuch"
848         if [ -x "$bin" ]; then
849             echo "$dir"
850             return
851         fi
852         dir="$(dirname "$dir")"
853         if [ "$dir" = "/" ]; then
854             break
855         fi
856     done
857 }
858
859 # Test the binaries we have just built.  The tests are kept in
860 # test/ subdirectory and are run in 'trash directory' subdirectory.
861 TEST_DIRECTORY=$(pwd)
862 if test -n "$valgrind"
863 then
864         make_symlink () {
865                 test -h "$2" &&
866                 test "$1" = "$(readlink "$2")" || {
867                         # be super paranoid
868                         if mkdir "$2".lock
869                         then
870                                 rm -f "$2" &&
871                                 ln -s "$1" "$2" &&
872                                 rm -r "$2".lock
873                         else
874                                 while test -d "$2".lock
875                                 do
876                                         say "Waiting for lock on $2."
877                                         sleep 1
878                                 done
879                         fi
880                 }
881         }
882
883         make_valgrind_symlink () {
884                 # handle only executables
885                 test -x "$1" || return
886
887                 base=$(basename "$1")
888                 symlink_target=$TEST_DIRECTORY/../$base
889                 # do not override scripts
890                 if test -x "$symlink_target" &&
891                     test ! -d "$symlink_target" &&
892                     test "#!" != "$(head -c 2 < "$symlink_target")"
893                 then
894                         symlink_target=../valgrind.sh
895                 fi
896                 case "$base" in
897                 *.sh|*.perl)
898                         symlink_target=../unprocessed-script
899                 esac
900                 # create the link, or replace it if it is out of date
901                 make_symlink "$symlink_target" "$GIT_VALGRIND/bin/$base" || exit
902         }
903
904         # override notmuch executable in TEST_DIRECTORY/..
905         GIT_VALGRIND=$TEST_DIRECTORY/valgrind
906         mkdir -p "$GIT_VALGRIND"/bin
907         make_valgrind_symlink $TEST_DIRECTORY/../notmuch
908         OLDIFS=$IFS
909         IFS=:
910         for path in $PATH
911         do
912                 ls "$path"/notmuch 2> /dev/null |
913                 while read file
914                 do
915                         make_valgrind_symlink "$file"
916                 done
917         done
918         IFS=$OLDIFS
919         PATH=$GIT_VALGRIND/bin:$PATH
920         GIT_EXEC_PATH=$GIT_VALGRIND/bin
921         export GIT_VALGRIND
922 else # normal case
923         notmuch_path=`find_notmuch_path "$TEST_DIRECTORY"`
924         test -n "$notmuch_path" && PATH="$notmuch_path:$PATH"
925 fi
926 export PATH
927
928 # Test repository
929 test="tmp.$(basename "$0" .sh)"
930 test -n "$root" && test="$root/$test"
931 case "$test" in
932 /*) TMP_DIRECTORY="$test" ;;
933  *) TMP_DIRECTORY="$TEST_DIRECTORY/$test" ;;
934 esac
935 test ! -z "$debug" || remove_tmp=$TMP_DIRECTORY
936 rm -fr "$test" || {
937         GIT_EXIT_OK=t
938         echo >&5 "FATAL: Cannot prepare test area"
939         exit 1
940 }
941
942 MAIL_DIR="${TMP_DIRECTORY}/mail"
943 export NOTMUCH_CONFIG="${TMP_DIRECTORY}/notmuch-config"
944
945 mkdir -p "${test}"
946 mkdir -p "${MAIL_DIR}"
947
948 cat <<EOF >"${NOTMUCH_CONFIG}"
949 [database]
950 path=${MAIL_DIR}
951
952 [user]
953 name=Notmuch Test Suite
954 primary_email=test_suite@notmuchmail.org
955 other_email=test_suite_other@notmuchmail.org;test_suite@otherdomain.org
956 EOF
957
958
959 # Use -P to resolve symlinks in our working directory so that the cwd
960 # in subprocesses like git equals our $PWD (for pathname comparisons).
961 cd -P "$test" || error "Cannot setup test environment"
962
963 if test "$verbose" = "t"
964 then
965         exec 4>&2 3>&1
966 else
967         exec 4>test.output 3>&4
968 fi
969
970 this_test=${0##*/}
971 for skp in $NOTMUCH_SKIP_TESTS
972 do
973         to_skip=
974         for skp in $NOTMUCH_SKIP_TESTS
975         do
976                 case "$this_test" in
977                 $skp)
978                         to_skip=t
979                 esac
980         done
981         case "$to_skip" in
982         t)
983                 say_color skip >&3 "skipping test $this_test altogether"
984                 say_color skip "skip all tests in $this_test"
985                 test_done
986         esac
987 done
988
989 # Provide an implementation of the 'yes' utility
990 yes () {
991         if test $# = 0
992         then
993                 y=y
994         else
995                 y="$*"
996         fi
997
998         while echo "$y"
999         do
1000                 :
1001         done
1002 }
1003
1004 # Fix some commands on Windows
1005 case $(uname -s) in
1006 *MINGW*)
1007         # Windows has its own (incompatible) sort and find
1008         sort () {
1009                 /usr/bin/sort "$@"
1010         }
1011         find () {
1012                 /usr/bin/find "$@"
1013         }
1014         sum () {
1015                 md5sum "$@"
1016         }
1017         # git sees Windows-style pwd
1018         pwd () {
1019                 builtin pwd -W
1020         }
1021         # no POSIX permissions
1022         # backslashes in pathspec are converted to '/'
1023         # exec does not inherit the PID
1024         ;;
1025 *)
1026         test_set_prereq POSIXPERM
1027         test_set_prereq BSLASHPSPEC
1028         test_set_prereq EXECKEEPSPID
1029         ;;
1030 esac
1031
1032 test -z "$NO_PERL" && test_set_prereq PERL
1033 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1034
1035 # test whether the filesystem supports symbolic links
1036 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1037 rm -f y