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