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