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