]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
350246492d8c2dbd0e6faf16c9dc26d19a77223c
[notmuch] / test / test-lib.sh
1 #
2 # Copyright (c) 2005 Junio C Hamano
3 # Copyright (c) 2010 Notmuch Developers
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 https://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 # Make sure echo builtin does not expand backslash-escape sequences by default.
27 shopt -u xpg_echo
28
29 this_test=${0##*/}
30 this_test=${this_test%.sh}
31 this_test_bare=${this_test#T[0-9][0-9][0-9]-}
32
33 # if --tee was passed, write the output not only to the terminal, but
34 # additionally to the file test-results/$BASENAME.out, too.
35 case "$GIT_TEST_TEE_STARTED, $* " in
36 done,*)
37         # do not redirect again
38         ;;
39 *' --tee '*|*' --va'*)
40         mkdir -p test-results
41         BASE=test-results/$this_test
42         (GIT_TEST_TEE_STARTED=done "$BASH" "$0" "$@" 2>&1;
43          echo $? > $BASE.exit) | tee $BASE.out
44         test "$(cat $BASE.exit)" = 0
45         exit
46         ;;
47 esac
48
49 # Save STDOUT to fd 6 and STDERR to fd 7.
50 exec 6>&1 7>&2
51 # Make xtrace debugging (when used) use redirected STDERR, with verbose lead:
52 BASH_XTRACEFD=7
53 export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
54
55 # Keep the original TERM for say_color and test_emacs
56 ORIGINAL_TERM=$TERM
57
58 # Set SMART_TERM to vt100 for known dumb/unknown terminal.
59 # Otherwise use whatever TERM is currently used so that
60 # users' actual TERM environments are being used in tests.
61 case ${TERM-} in
62         '' | dumb | unknown )
63                 SMART_TERM=vt100 ;;
64         *)
65                 SMART_TERM=$TERM ;;
66 esac
67
68 # For repeatability, reset the environment to known value.
69 LANG=C
70 LC_ALL=C
71 PAGER=cat
72 TZ=UTC
73 TERM=dumb
74 export LANG LC_ALL PAGER TERM TZ
75 GIT_TEST_CMP=${GIT_TEST_CMP:-diff -u}
76 if [[ ( -n "$TEST_EMACS" && -z "$TEST_EMACSCLIENT" ) || \
77       ( -z "$TEST_EMACS" && -n "$TEST_EMACSCLIENT" ) ]]; then
78     echo "error: must specify both or neither of TEST_EMACS and TEST_EMACSCLIENT" >&2
79     exit 1
80 fi
81 TEST_EMACS=${TEST_EMACS:-${EMACS:-emacs}}
82 TEST_EMACSCLIENT=${TEST_EMACSCLIENT:-emacsclient}
83 TEST_GDB=${TEST_GDB:-gdb}
84 TEST_CC=${TEST_CC:-cc}
85 TEST_CFLAGS=${TEST_CFLAGS:-"-g -O0"}
86
87 # Protect ourselves from common misconfiguration to export
88 # CDPATH into the environment
89 unset CDPATH
90
91 unset GREP_OPTIONS
92
93 # For emacsclient
94 unset ALTERNATE_EDITOR
95
96 # Each test should start with something like this, after copyright notices:
97 #
98 # test_description='Description of this test...
99 # This test checks if command xyzzy does the right thing...
100 # '
101 # . ./test-lib.sh || exit 1
102
103 [ "x$ORIGINAL_TERM" != "xdumb" ] && (
104                 TERM=$ORIGINAL_TERM &&
105                 export TERM &&
106                 [ -t 1 ] &&
107                 tput bold >/dev/null 2>&1 &&
108                 tput setaf 1 >/dev/null 2>&1 &&
109                 tput sgr0 >/dev/null 2>&1
110         ) &&
111         color=t
112
113 while test "$#" -ne 0
114 do
115         case "$1" in
116         -d|--debug)
117                 debug=t; shift ;;
118         -i|--immediate)
119                 immediate=t; shift ;;
120         -h|--help)
121                 help=t; shift ;;
122         -v|--verbose)
123                 verbose=t; shift ;;
124         -q|--quiet)
125                 quiet=t; shift ;;
126         --with-dashes)
127                 with_dashes=t; shift ;;
128         --no-color)
129                 color=; shift ;;
130         --no-python)
131                 # noop now...
132                 shift ;;
133         --valgrind)
134                 valgrind=t; verbose=t; shift ;;
135         --tee)
136                 shift ;; # was handled already
137         --root=*)
138                 root=$(expr "z$1" : 'z[^=]*=\(.*\)')
139                 shift ;;
140         *)
141                 echo "error: unknown test option '$1'" >&2; exit 1 ;;
142         esac
143 done
144
145 if test -n "$debug"; then
146     print_subtest () {
147         printf " %-4s" "[$((test_count - 1))]"
148     }
149 else
150     print_subtest () {
151         true
152     }
153 fi
154
155 if test -n "$color"; then
156         say_color () {
157                 (
158                 TERM=$ORIGINAL_TERM
159                 export TERM
160                 case "$1" in
161                         error) tput bold; tput setaf 1;; # bold red
162                         skip)  tput bold; tput setaf 2;; # bold green
163                         pass)  tput setaf 2;;            # green
164                         info)  tput setaf 3;;            # brown
165                         *) test -n "$quiet" && return;;
166                 esac
167                 shift
168                 printf " "
169                 printf "$@"
170                 tput sgr0
171                 print_subtest
172                 )
173         }
174 else
175         say_color() {
176                 test -z "$1" && test -n "$quiet" && return
177                 shift
178                 printf " "
179                 printf "$@"
180                 print_subtest
181         }
182 fi
183
184 error () {
185         say_color error "error: $*\n"
186         GIT_EXIT_OK=t
187         exit 1
188 }
189
190 say () {
191         say_color info "$*"
192 }
193
194 test "${test_description}" != "" ||
195 error "Test script did not set test_description."
196
197 if test "$help" = "t"
198 then
199         echo "Tests ${test_description}"
200         exit 0
201 fi
202
203 test_description_printed=
204 print_test_description ()
205 {
206         test -z "$test_description_printed" || return 0
207         echo
208         echo $this_test: "Testing ${test_description}"
209         test_description_printed=1
210 }
211 if [ -z "$NOTMUCH_TEST_QUIET" ]
212 then
213         print_test_description
214 fi
215
216 test_failure=0
217 test_count=0
218 test_fixed=0
219 test_broken=0
220 test_success=0
221
222 declare -a _exit_functions=()
223
224 at_exit_function () {
225         _exit_functions=($1 ${_exit_functions[@]/$1})
226 }
227
228 rm_exit_function () {
229         _exit_functions=(${_exit_functions[@]/$1})
230 }
231
232 _exit_common () {
233         code=$?
234         trap - EXIT
235         set +ex
236         for _fn in ${_exit_functions[@]}; do $_fn; done
237         rm -rf "$TEST_TMPDIR"
238 }
239
240 trap_exit () {
241         _exit_common
242         if test -n "$GIT_EXIT_OK"
243         then
244                 exit $code
245         else
246                 exec >&6
247                 say_color error '%-6s' FATAL
248                 echo " $test_subtest_name"
249                 echo
250                 echo "Unexpected exit while executing $0. Exit code $code."
251                 exit 1
252         fi
253 }
254
255 trap_signal () {
256         _exit_common
257         echo >&6 "FATAL: $0: interrupted by signal" $((code - 128))
258         exit $code
259 }
260
261 die () {
262         _exit_common
263         exec >&6
264         say_color error '%-6s' FATAL
265         echo " $*"
266         echo
267         echo "Unexpected exit while executing $0."
268         exit 1
269 }
270
271 GIT_EXIT_OK=
272 # Note: TEST_TMPDIR *NOT* exported!
273 TEST_TMPDIR=$(mktemp -d "${TMPDIR:-/tmp}/notmuch-test-$$.XXXXXX")
274 # Put GNUPGHOME in TMPDIR to avoid problems with long paths.
275 export GNUPGHOME="${TEST_TMPDIR}/gnupg"
276 trap 'trap_exit' EXIT
277 trap 'trap_signal' HUP INT TERM
278
279 # Deliver a message with emacs and add it to the database
280 #
281 # Uses emacs to generate and deliver a message to the mail store.
282 # Accepts arbitrary extra emacs/elisp functions to modify the message
283 # before sending, which is useful to doing things like attaching files
284 # to the message and encrypting/signing.
285 emacs_deliver_message ()
286 {
287     local subject="$1"
288     local body="$2"
289     shift 2
290     # before we can send a message, we have to prepare the FCC maildir
291     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
292     # eval'ing smtp-dummy --background will set smtp_dummy_pid
293     smtp_dummy_pid=
294     eval `$TEST_DIRECTORY/smtp-dummy --background sent_message`
295     test -n "$smtp_dummy_pid" || return 1
296
297     test_emacs \
298         "(let ((message-send-mail-function 'message-smtpmail-send-it)
299                (mail-host-address \"example.com\")
300                (smtpmail-smtp-server \"localhost\")
301                (smtpmail-smtp-service \"25025\"))
302            (notmuch-mua-mail)
303            (message-goto-to)
304            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
305            (message-goto-subject)
306            (insert \"${subject}\")
307            (message-goto-body)
308            (insert \"${body}\")
309            $@
310            (notmuch-mua-send-and-exit))"
311
312     # In case message was sent properly, client waits for confirmation
313     # before exiting and resuming control here; therefore making sure
314     # that server exits by sending (KILL) signal to it is safe.
315     kill -9 $smtp_dummy_pid
316     notmuch new >/dev/null
317 }
318
319 # Pretend to deliver a message with emacs. Really save it to a file
320 # and add it to the database
321 #
322 # Uses emacs to generate and deliver a message to the mail store.
323 # Accepts arbitrary extra emacs/elisp functions to modify the message
324 # before sending, which is useful to doing things like attaching files
325 # to the message and encrypting/signing.
326 emacs_fcc_message ()
327 {
328     local subject="$1"
329     local body="$2"
330     shift 2
331     # before we can send a message, we have to prepare the FCC maildir
332     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
333
334     test_emacs \
335         "(let ((message-send-mail-function (lambda () t))
336                (mail-host-address \"example.com\"))
337            (notmuch-mua-mail)
338            (message-goto-to)
339            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
340            (message-goto-subject)
341            (insert \"${subject}\")
342            (message-goto-body)
343            (insert \"${body}\")
344            $@
345            (notmuch-mua-send-and-exit))" || return 1
346     notmuch new >/dev/null
347 }
348
349 # Add an existing, fixed corpus of email to the database.
350 #
351 # $1 is the corpus dir under corpora to add, using "default" if unset.
352 #
353 # The default corpus is based on about 50 messages from early in the
354 # history of the notmuch mailing list, which allows for reliably
355 # testing commands that need to operate on a not-totally-trivial
356 # number of messages.
357 add_email_corpus ()
358 {
359     corpus=${1:-default}
360
361     rm -rf ${MAIL_DIR}
362     if [ -d $TEST_DIRECTORY/corpora.mail/$corpus ]; then
363         cp -a $TEST_DIRECTORY/corpora.mail/$corpus ${MAIL_DIR}
364     else
365         cp -a $TEST_DIRECTORY/corpora/$corpus ${MAIL_DIR}
366         notmuch new >/dev/null || die "'notmuch new' failed while adding email corpus"
367         mkdir -p $TEST_DIRECTORY/corpora.mail
368         cp -a ${MAIL_DIR} $TEST_DIRECTORY/corpora.mail/$corpus
369     fi
370 }
371
372 test_begin_subtest ()
373 {
374     if [ -n "$inside_subtest" ]; then
375         exec 1>&6 2>&7          # Restore stdout and stderr
376         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
377     fi
378     test_subtest_name="$1"
379     test_reset_state_
380     # Redirect test output to the previously prepared file descriptors
381     # 3 and 4 (see below)
382     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
383     exec >&3 2>&4
384     inside_subtest=t
385 }
386
387 # Pass test if two arguments match
388 #
389 # Note: Unlike all other test_expect_* functions, this function does
390 # not accept a test name. Instead, the caller should call
391 # test_begin_subtest before calling this function in order to set the
392 # name.
393 test_expect_equal ()
394 {
395         exec 1>&6 2>&7          # Restore stdout and stderr
396         if [ -z "$inside_subtest" ]; then
397                 error "bug in the test script: test_expect_equal without test_begin_subtest"
398         fi
399         inside_subtest=
400         test "$#" = 2 ||
401         error "bug in the test script: not 2 parameters to test_expect_equal"
402
403         output="$1"
404         expected="$2"
405         if ! test_skip "$test_subtest_name"
406         then
407                 if [ "$output" = "$expected" ]; then
408                         test_ok_
409                 else
410                         testname=$this_test.$test_count
411                         echo "$expected" > $testname.expected
412                         echo "$output" > $testname.output
413                         test_failure_ "$(diff -u $testname.expected $testname.output)"
414                 fi
415     fi
416 }
417
418 # Like test_expect_equal, but takes two filenames.
419 test_expect_equal_file ()
420 {
421         exec 1>&6 2>&7          # Restore stdout and stderr
422         if [ -z "$inside_subtest" ]; then
423                 error "bug in the test script: test_expect_equal_file without test_begin_subtest"
424         fi
425         inside_subtest=
426         test "$#" = 2 ||
427         error "bug in the test script: not 2 parameters to test_expect_equal_file"
428
429         file1="$1"
430         file2="$2"
431         if ! test_skip "$test_subtest_name"
432         then
433                 if diff -q "$file1" "$file2" >/dev/null ; then
434                         test_ok_
435                 else
436                         testname=$this_test.$test_count
437                         basename1=`basename "$file1"`
438                         basename2=`basename "$file2"`
439                         cp "$file1" "$testname.$basename1"
440                         cp "$file2" "$testname.$basename2"
441                         test_failure_ "$(diff -u "$testname.$basename1" "$testname.$basename2")"
442                 fi
443     fi
444 }
445
446 # Like test_expect_equal, but arguments are JSON expressions to be
447 # canonicalized before diff'ing.  If an argument cannot be parsed, it
448 # is used unchanged so that there's something to diff against.
449 test_expect_equal_json () {
450     # The test suite forces LC_ALL=C, but this causes Python 3 to
451     # decode stdin as ASCII.  We need to read JSON in UTF-8, so
452     # override Python's stdio encoding defaults.
453     local script='import json, sys; json.dump(json.load(sys.stdin), sys.stdout, sort_keys=True, indent=4)'
454     output=$(echo "$1" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c "$script" \
455         || echo "$1")
456     expected=$(echo "$2" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c "$script" \
457         || echo "$2")
458     shift 2
459     test_expect_equal "$output" "$expected" "$@"
460 }
461
462 # Sort the top-level list of JSON data from stdin.
463 test_sort_json () {
464     PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c \
465         "import sys, json; json.dump(sorted(json.load(sys.stdin)),sys.stdout)"
466 }
467
468 test_emacs_expect_t () {
469         test "$#" = 1 ||
470         error "bug in the test script: not 1 parameter to test_emacs_expect_t"
471         if [ -z "$inside_subtest" ]; then
472                 error "bug in the test script: test_emacs_expect_t without test_begin_subtest"
473         fi
474
475         # Run the test.
476         if ! test_skip "$test_subtest_name"
477         then
478                 test_emacs "(notmuch-test-run $1)" >/dev/null
479
480                 # Restore state after the test.
481                 exec 1>&6 2>&7          # Restore stdout and stderr
482                 inside_subtest=
483
484                 # Report success/failure.
485                 result=$(cat OUTPUT)
486                 if [ "$result" = t ]
487                 then
488                         test_ok_
489                 else
490                         test_failure_ "${result}"
491                 fi
492         else
493                 # Restore state after the (non) test.
494                 exec 1>&6 2>&7          # Restore stdout and stderr
495                 inside_subtest=
496         fi
497 }
498
499 NOTMUCH_NEW ()
500 {
501     notmuch new "${@}" | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
502 }
503
504 NOTMUCH_DUMP_TAGS ()
505 {
506     # this relies on the default format being batch-tag, otherwise some tests will break
507     notmuch dump --include=tags "${@}" | sed '/^#/d' | sort
508 }
509
510 notmuch_drop_mail_headers ()
511 {
512     $NOTMUCH_PYTHON -c '
513 import email, sys
514 msg = email.message_from_file(sys.stdin)
515 for hdr in sys.argv[1:]: del msg[hdr]
516 print(msg.as_string(False))
517 ' "$@"
518 }
519
520 notmuch_search_sanitize ()
521 {
522     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
523 }
524
525 notmuch_search_files_sanitize ()
526 {
527     notmuch_dir_sanitize
528 }
529
530 notmuch_dir_sanitize ()
531 {
532     sed -e "s,$MAIL_DIR,MAIL_DIR," -e "s,${PWD},CWD,g" "$@"
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         notmuch_date_sanitize
546 }
547
548 notmuch_json_show_sanitize ()
549 {
550     sed \
551         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
552         -e 's|"Date": "Fri, 05 Jan 2001 [^"]*0000"|"Date": "GENERATED_DATE"|g' \
553         -e 's|"filename": "signature.asc",||g' \
554         -e 's|"filename": \["/[^"]*"\],|"filename": \["YYYYY"\],|g' \
555         -e 's|"timestamp": 97.......|"timestamp": 42|g' \
556         -e 's|"content-length": [1-9][0-9]*|"content-length": "NONZERO"|g'
557 }
558
559 notmuch_emacs_error_sanitize ()
560 {
561     local command=$1
562     shift
563     for file in "$@"; do
564         echo "=== $file ==="
565         cat "$file"
566     done | sed  \
567         -e 's/^\[.*\]$/[XXX]/' \
568         -e "s|^\(command: \)\{0,1\}/.*/$command|\1YYY/$command|"
569 }
570
571 notmuch_date_sanitize ()
572 {
573     sed \
574         -e 's/^Date: Fri, 05 Jan 2001 .*0000/Date: GENERATED_DATE/'
575 }
576
577 notmuch_uuid_sanitize ()
578 {
579     sed 's/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}/UUID/g'
580 }
581
582 notmuch_built_with_sanitize ()
583 {
584     sed 's/^built_with[.]\(.*\)=.*$/built_with.\1=something/'
585 }
586
587 notmuch_config_sanitize ()
588 {
589     notmuch_dir_sanitize | notmuch_built_with_sanitize
590 }
591
592 # End of notmuch helper functions
593
594 # Use test_set_prereq to tell that a particular prerequisite is available.
595 #
596 # The prerequisite can later be checked for by using test_have_prereq.
597 #
598 # The single parameter is the prerequisite tag (a simple word, in all
599 # capital letters by convention).
600
601 test_set_prereq () {
602         satisfied="$satisfied$1 "
603 }
604 satisfied=" "
605
606 test_have_prereq () {
607         case $satisfied in
608         *" $1 "*)
609                 : yes, have it ;;
610         *)
611                 ! : nope ;;
612         esac
613 }
614
615 declare -A test_missing_external_prereq_
616 declare -A test_subtest_missing_external_prereq_
617
618 # declare prerequisite for the given external binary
619 test_declare_external_prereq () {
620         binary="$1"
621         test "$#" = 2 && name=$2 || name="$binary(1)"
622
623         if ! hash $binary 2>/dev/null; then
624                 test_missing_external_prereq_["${binary}"]=t
625                 eval "
626 $binary () {
627         test_subtest_missing_external_prereq_[\"${name}\"]=t
628         false
629 }"
630         fi
631 }
632
633 # Explicitly require external prerequisite.  Useful when binary is
634 # called indirectly (e.g. from emacs).
635 # Returns success if dependency is available, failure otherwise.
636 test_require_external_prereq () {
637         binary="$1"
638         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
639                 # dependency is missing, call the replacement function to note it
640                 eval "$binary"
641         else
642                 true
643         fi
644 }
645
646 # You are not expected to call test_ok_ and test_failure_ directly, use
647 # the text_expect_* functions instead.
648
649 test_ok_ () {
650         if test "$test_subtest_known_broken_" = "t"; then
651                 test_known_broken_ok_
652                 return
653         fi
654         test_success=$(($test_success + 1))
655         if test -n "$NOTMUCH_TEST_QUIET"; then
656                 return 0
657         fi
658         say_color pass "%-6s" "PASS"
659         echo " $test_subtest_name"
660 }
661
662 test_failure_ () {
663         print_test_description
664         if test "$test_subtest_known_broken_" = "t"; then
665                 test_known_broken_failure_ "$@"
666                 return
667         fi
668         test_failure=$(($test_failure + 1))
669         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
670         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
671         return 1
672 }
673
674 test_failure_message_ () {
675         say_color error "%-6s" "$1"
676         echo " $2"
677         shift 2
678         if [ "$#" != "0" ]; then
679                 echo "$@" | sed -e 's/^/        /'
680         fi
681         if test "$verbose" != "t"; then cat test.output; fi
682 }
683
684 test_known_broken_ok_ () {
685         test_reset_state_
686         test_fixed=$(($test_fixed+1))
687         say_color pass "%-6s" "FIXED"
688         echo " $test_subtest_name"
689 }
690
691 test_known_broken_failure_ () {
692         test_reset_state_
693         test_broken=$(($test_broken+1))
694         if [ -z "$NOTMUCH_TEST_QUIET" ]; then
695                 test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
696         else
697                 test_failure_message_ "BROKEN" "$test_subtest_name"
698         fi
699         return 1
700 }
701
702 test_debug () {
703         test "$debug" = "" || eval "$1"
704 }
705
706 test_run_ () {
707         test_cleanup=:
708         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
709         eval >&3 2>&4 "$1"
710         eval_ret=$?
711         eval >&3 2>&4 "$test_cleanup"
712         return 0
713 }
714
715 test_skip () {
716         test_count=$(($test_count+1))
717         to_skip=
718         for skp in $NOTMUCH_SKIP_TESTS
719         do
720                 case $this_test.$test_count in
721                 $skp)
722                         to_skip=t
723                         break
724                 esac
725                 case $this_test_bare.$test_count in
726                 $skp)
727                         to_skip=t
728                         break
729                 esac
730         done
731         case "$to_skip" in
732         t)
733                 test_report_skip_ "$@"
734                 ;;
735         *)
736                 test_check_missing_external_prereqs_ "$@"
737                 ;;
738         esac
739 }
740
741 test_check_missing_external_prereqs_ () {
742         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
743                 say_color skip >&1 "missing prerequisites: "
744                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
745                 test_report_skip_ "$@"
746         else
747                 false
748         fi
749 }
750
751 test_report_skip_ () {
752         test_reset_state_
753         say_color skip >&3 "skipping test:"
754         echo " $@" >&3
755         say_color skip "%-6s" "SKIP"
756         echo " $1"
757 }
758
759 test_subtest_known_broken () {
760         test_subtest_known_broken_=t
761 }
762
763 test_expect_success () {
764         exec 1>&6 2>&7          # Restore stdout and stderr
765         if [ -z "$inside_subtest" ]; then
766                 error "bug in the test script: test_expect_success without test_begin_subtest"
767         fi
768         inside_subtest=
769         test "$#" = 1 ||
770         error "bug in the test script: not 1 parameters to test_expect_success"
771
772         if ! test_skip "$test_subtest_name"
773         then
774                 test_run_ "$1"
775                 run_ret="$?"
776                 # test_run_ may update missing external prerequisites
777                 test_check_missing_external_prereqs_ "$@" ||
778                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
779                 then
780                         test_ok_
781                 else
782                         test_failure_ "$1"
783                 fi
784         fi
785 }
786
787 test_expect_code () {
788         exec 1>&6 2>&7          # Restore stdout and stderr
789         if [ -z "$inside_subtest" ]; then
790                 error "bug in the test script: test_expect_code without test_begin_subtest"
791         fi
792         inside_subtest=
793         test "$#" = 2 ||
794         error "bug in the test script: not 2 parameters to test_expect_code"
795
796         if ! test_skip "$test_subtest_name"
797         then
798                 test_run_ "$2"
799                 run_ret="$?"
800                 # test_run_ may update missing external prerequisites,
801                 test_check_missing_external_prereqs_ "$@" ||
802                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
803                 then
804                         test_ok_
805                 else
806                         test_failure_ "exit code $eval_ret, expected $1" "$2"
807                 fi
808         fi
809 }
810
811 # This is not among top-level (test_expect_success)
812 # but is a prefix that can be used in the test script, like:
813 #
814 #       test_expect_success 'complain and die' '
815 #           do something &&
816 #           do something else &&
817 #           test_must_fail git checkout ../outerspace
818 #       '
819 #
820 # Writing this as "! git checkout ../outerspace" is wrong, because
821 # the failure could be due to a segv.  We want a controlled failure.
822
823 test_must_fail () {
824         "$@"
825         test $? -gt 0 -a $? -le 129 -o $? -gt 192
826 }
827
828 # test_cmp is a helper function to compare actual and expected output.
829 # You can use it like:
830 #
831 #       test_expect_success 'foo works' '
832 #               echo expected >expected &&
833 #               foo >actual &&
834 #               test_cmp expected actual
835 #       '
836 #
837 # This could be written as either "cmp" or "diff -u", but:
838 # - cmp's output is not nearly as easy to read as diff -u
839 # - not all diff versions understand "-u"
840
841 test_cmp() {
842         $GIT_TEST_CMP "$@"
843 }
844
845 # This function can be used to schedule some commands to be run
846 # unconditionally at the end of the test to restore sanity:
847 #
848 #       test_expect_success 'test core.capslock' '
849 #               git config core.capslock true &&
850 #               test_when_finished "git config --unset core.capslock" &&
851 #               hello world
852 #       '
853 #
854 # That would be roughly equivalent to
855 #
856 #       test_expect_success 'test core.capslock' '
857 #               git config core.capslock true &&
858 #               hello world
859 #               git config --unset core.capslock
860 #       '
861 #
862 # except that the greeting and config --unset must both succeed for
863 # the test to pass.
864
865 test_when_finished () {
866         test_cleanup="{ $*
867                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
868 }
869
870 test_done () {
871         GIT_EXIT_OK=t
872         test_results_dir="$TEST_DIRECTORY/test-results"
873         mkdir -p "$test_results_dir"
874         test_results_path="$test_results_dir/$this_test"
875
876         echo "total $test_count" >> $test_results_path
877         echo "success $test_success" >> $test_results_path
878         echo "fixed $test_fixed" >> $test_results_path
879         echo "broken $test_broken" >> $test_results_path
880         echo "failed $test_failure" >> $test_results_path
881         echo "" >> $test_results_path
882
883         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
884
885         if [ "$test_failure" = "0" ]; then
886             if [ "$test_broken" = "0" ]; then
887                 rm -rf "$remove_tmp"
888             fi
889             exit 0
890         else
891             exit 1
892         fi
893 }
894
895 emacs_generate_script () {
896         # Construct a little test script here for the benefit of the user,
897         # (who can easily run "run_emacs" to get the same emacs environment
898         # for investigating any failures).
899         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
900 #!/bin/sh
901 export PATH=$PATH
902 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
903
904 # Here's what we are using here:
905 #
906 # --quick              Use minimal customization. This implies --no-init-file,
907 #                      --no-site-file and (emacs 24) --no-site-lisp
908 #
909 # --directory           Ensure that the local elisp sources are found
910 #
911 # --load                Force loading of notmuch.el and test-lib.el
912
913 exec ${TEST_EMACS} --quick \
914         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
915         --directory "$TEST_DIRECTORY" --load test-lib.el \
916         "\$@"
917 EOF
918         chmod a+x "$TMP_DIRECTORY/run_emacs"
919 }
920
921 test_emacs () {
922         # test dependencies beforehand to avoid the waiting loop below
923         missing_dependencies=
924         test_require_external_prereq dtach || missing_dependencies=1
925         test_require_external_prereq emacs || missing_dependencies=1
926         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
927         test -z "$missing_dependencies" || return
928
929         if [ -z "$EMACS_SERVER" ]; then
930                 emacs_tests="${this_test_bare}.el"
931                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
932                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
933                 else
934                         load_emacs_tests=
935                 fi
936                 server_name="notmuch-test-suite-$$"
937                 # start a detached session with an emacs server
938                 # user's TERM (or 'vt100' in case user's TERM is known dumb
939                 # or unknown) is given to dtach which assumes a minimally
940                 # VT100-compatible terminal -- and emacs inherits that
941                 TERM=$SMART_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
942                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
943                                 --no-window-system \
944                                 $load_emacs_tests \
945                                 --eval '(setq server-name \"$server_name\")' \
946                                 --eval '(server-start)' \
947                                 --eval '(orphan-watchdog $$)'" || return
948                 EMACS_SERVER="$server_name"
949                 # wait until the emacs server is up
950                 until test_emacs '()' >/dev/null 2>/dev/null; do
951                         sleep 1
952                 done
953         fi
954
955         # Clear test-output output file.  Most Emacs tests end with a
956         # call to (test-output).  If the test code fails with an
957         # exception before this call, the output file won't get
958         # updated.  Since we don't want to compare against an output
959         # file from another test, so start out with an empty file.
960         rm -f OUTPUT
961         touch OUTPUT
962
963         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(notmuch-test-progn $@)"
964 }
965
966 test_python() {
967     # Note: if there is need to print debug information from python program,
968     # use stdout = os.fdopen(6, 'w') or stderr = os.fdopen(7, 'w')
969     PYTHONPATH="$NOTMUCH_SRCDIR/bindings/python${PYTHONPATH:+:$PYTHONPATH}" \
970         $NOTMUCH_PYTHON -B - > OUTPUT
971 }
972
973 test_ruby() {
974     MAIL_DIR=$MAIL_DIR ruby -I $TEST_DIRECTORY/../bindings/ruby> OUTPUT
975 }
976
977 test_C () {
978     exec_file="test${test_count}"
979     test_file="${exec_file}.c"
980     cat > ${test_file}
981     ${TEST_CC} ${TEST_CFLAGS} -I${TEST_DIRECTORY} -I${NOTMUCH_SRCDIR}/lib -o ${exec_file} ${test_file} -L${TEST_DIRECTORY}/../lib/ -lnotmuch -ltalloc
982     echo "== stdout ==" > OUTPUT.stdout
983     echo "== stderr ==" > OUTPUT.stderr
984     ./${exec_file} "$@" 1>>OUTPUT.stdout 2>>OUTPUT.stderr
985     notmuch_dir_sanitize OUTPUT.stdout OUTPUT.stderr > OUTPUT
986 }
987
988
989 # Creates a script that counts how much time it is executed and calls
990 # notmuch.  $notmuch_counter_command is set to the path to the
991 # generated script.  Use notmuch_counter_value() function to get the
992 # current counter value.
993 notmuch_counter_reset () {
994         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
995         if [ ! -x "$notmuch_counter_command" ]; then
996                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
997                 cat >"$notmuch_counter_command" <<EOF || return
998 #!/bin/sh
999
1000 read count < "$notmuch_counter_state_path"
1001 echo \$((count + 1)) > "$notmuch_counter_state_path"
1002
1003 exec notmuch "\$@"
1004 EOF
1005                 chmod +x "$notmuch_counter_command" || return
1006         fi
1007
1008         echo 0 > "$notmuch_counter_state_path"
1009 }
1010
1011 # Returns the current notmuch counter value.
1012 notmuch_counter_value () {
1013         if [ -r "$notmuch_counter_state_path" ]; then
1014                 read count < "$notmuch_counter_state_path"
1015         else
1016                 count=0
1017         fi
1018         echo $count
1019 }
1020
1021 test_reset_state_ () {
1022         test -z "$test_init_done_" && test_init_
1023
1024         test_subtest_known_broken_=
1025         test_subtest_missing_external_prereq_=()
1026 }
1027
1028 # called once before the first subtest
1029 test_init_ () {
1030         test_init_done_=t
1031
1032         # skip all tests if there were external prerequisites missing during init
1033         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1034 }
1035
1036
1037 . ./test-lib-common.sh || exit 1
1038
1039 if [ "${NOTMUCH_GMIME_MAJOR}" = 3 ]; then
1040     test_subtest_broken_gmime_3 () {
1041         test_subtest_known_broken
1042     }
1043     test_subtest_broken_gmime_2 () {
1044         true
1045     }
1046 else
1047     test_subtest_broken_gmime_3 () {
1048         true
1049     }
1050     test_subtest_broken_gmime_2 () {
1051         test_subtest_known_broken
1052     }
1053 fi
1054
1055 emacs_generate_script
1056
1057
1058 # Use -P to resolve symlinks in our working directory so that the cwd
1059 # in subprocesses like git equals our $PWD (for pathname comparisons).
1060 cd -P "$test" || error "Cannot set up test environment"
1061
1062 if test "$verbose" = "t"
1063 then
1064         exec 4>&2 3>&1
1065 else
1066         exec 4>test.output 3>&4
1067 fi
1068
1069 for skp in $NOTMUCH_SKIP_TESTS
1070 do
1071         to_skip=
1072         for skp in $NOTMUCH_SKIP_TESTS
1073         do
1074                 case "$this_test" in
1075                 $skp)
1076                         to_skip=t
1077                         break
1078                 esac
1079                 case "$this_test_bare" in
1080                 $skp)
1081                         to_skip=t
1082                         break
1083                 esac
1084         done
1085         case "$to_skip" in
1086         t)
1087                 say_color skip >&3 "skipping test $this_test altogether"
1088                 say_color skip "skip all tests in $this_test"
1089                 test_done
1090         esac
1091 done
1092
1093 # Provide an implementation of the 'yes' utility
1094 yes () {
1095         if test $# = 0
1096         then
1097                 y=y
1098         else
1099                 y="$*"
1100         fi
1101
1102         while echo "$y"
1103         do
1104                 :
1105         done
1106 }
1107
1108 # Fix some commands on Windows
1109 case $(uname -s) in
1110 *MINGW*)
1111         # Windows has its own (incompatible) sort and find
1112         sort () {
1113                 /usr/bin/sort "$@"
1114         }
1115         find () {
1116                 /usr/bin/find "$@"
1117         }
1118         sum () {
1119                 md5sum "$@"
1120         }
1121         # git sees Windows-style pwd
1122         pwd () {
1123                 builtin pwd -W
1124         }
1125         # no POSIX permissions
1126         # backslashes in pathspec are converted to '/'
1127         # exec does not inherit the PID
1128         ;;
1129 *)
1130         test_set_prereq POSIXPERM
1131         test_set_prereq BSLASHPSPEC
1132         test_set_prereq EXECKEEPSPID
1133         ;;
1134 esac
1135
1136 test -z "$NO_PERL" && test_set_prereq PERL
1137 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1138
1139 # test whether the filesystem supports symbolic links
1140 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1141 rm -f y
1142
1143 # convert variable from configure to more convenient form
1144 case "$NOTMUCH_DEFAULT_XAPIAN_BACKEND" in
1145     glass)
1146         db_ending=glass
1147     ;;
1148     chert)
1149         db_ending=DB
1150     ;;
1151     *)
1152         error "Unknown Xapian backend $NOTMUCH_DEFAULT_XAPIAN_BACKEND"
1153 esac
1154 # declare prerequisites for external binaries used in tests
1155 test_declare_external_prereq dtach
1156 test_declare_external_prereq emacs
1157 test_declare_external_prereq ${TEST_EMACSCLIENT}
1158 test_declare_external_prereq ${TEST_GDB}
1159 test_declare_external_prereq gpg
1160 test_declare_external_prereq openssl
1161 test_declare_external_prereq gpgsm
1162 test_declare_external_prereq ${NOTMUCH_PYTHON}