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