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