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