]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: replace notmuch_passwd_sanitize() with _libconfig_sanitize()
[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     print_subtest () {
197         printf " %-4s" "[$((test_count - 1))]"
198     }
199 else
200     print_subtest () {
201         true
202     }
203 fi
204
205 test -n "$COLORS_WITHOUT_TTY" || [ -t 1 ] || color=
206
207 if [ -n "$color" ] && [ "$ORIGINAL_TERM" != 'dumb' ] && (
208                 TERM=$ORIGINAL_TERM &&
209                 export TERM &&
210                 tput bold
211                 tput setaf
212                 tput sgr0
213         ) >/dev/null 2>&1
214 then
215         color=t
216 else
217         color=
218 fi
219
220 if test -n "$color"; then
221         say_color () {
222                 (
223                 TERM=$ORIGINAL_TERM
224                 export TERM
225                 case "$1" in
226                         error) tput bold; tput setaf 1;; # bold red
227                         skip)  tput bold; tput setaf 2;; # bold green
228                         pass)  tput setaf 2;;            # green
229                         info)  tput setaf 3;;            # brown
230                         *) test -n "$quiet" && return;;
231                 esac
232                 shift
233                 printf " "
234                 printf "$@"
235                 tput sgr0
236                 print_subtest
237                 )
238         }
239 else
240         say_color() {
241                 test -z "$1" && test -n "$quiet" && return
242                 shift
243                 printf " "
244                 printf "$@"
245                 print_subtest
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 # Like test_expect_equal, but takes two filenames.
406 test_expect_equal_file () {
407         local file1 file2 testname basename1 basename2
408         exec 1>&6 2>&7          # Restore stdout and stderr
409         if [ -z "$inside_subtest" ]; then
410                 error "bug in the test script: test_expect_equal_file without test_begin_subtest"
411         fi
412         inside_subtest=
413         test "$#" = 2 ||
414         error "bug in the test script: not 2 parameters to test_expect_equal_file"
415
416         file1="$1"
417         file2="$2"
418         if ! test_skip "$test_subtest_name"
419         then
420                 if diff -q "$file1" "$file2" >/dev/null ; then
421                         test_ok_
422                 else
423                         testname=$this_test.$test_count
424                         basename1=`basename "$file1"`
425                         basename2=`basename "$file2"`
426                         cp "$file1" "$testname.$basename1"
427                         cp "$file2" "$testname.$basename2"
428                         test_failure_ "$(diff -u "$testname.$basename1" "$testname.$basename2")"
429                 fi
430     fi
431 }
432
433 # Like test_expect_equal, but arguments are JSON expressions to be
434 # canonicalized before diff'ing.  If an argument cannot be parsed, it
435 # is used unchanged so that there's something to diff against.
436 test_expect_equal_json () {
437     local script output expected
438     # The test suite forces LC_ALL=C, but this causes Python 3 to
439     # decode stdin as ASCII.  We need to read JSON in UTF-8, so
440     # override Python's stdio encoding defaults.
441     script='import json, sys; json.dump(json.load(sys.stdin), sys.stdout, sort_keys=True, indent=4)'
442     output=$(echo "$1" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c "$script" \
443         || echo "$1")
444     expected=$(echo "$2" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c "$script" \
445         || echo "$2")
446     shift 2
447     test_expect_equal "$output" "$expected" "$@"
448 }
449
450 # Ensure that the argument is valid JSON data.
451 test_valid_json () {
452     PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c "import sys, json; json.load(sys.stdin)" <<<"$1"
453     test_expect_equal "$?" 0
454 }
455
456 # Sort the top-level list of JSON data from stdin.
457 test_sort_json () {
458     PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c \
459         "import sys, json; json.dump(sorted(json.load(sys.stdin)),sys.stdout)"
460 }
461
462 # test for json objects:
463 # read the source of test/json_check_nodes.py (or the output when
464 # invoking it without arguments) for an explanation of the syntax.
465 test_json_nodes () {
466         local output
467         exec 1>&6 2>&7          # Restore stdout and stderr
468         if [ -z "$inside_subtest" ]; then
469                 error "bug in the test script: test_json_eval without test_begin_subtest"
470         fi
471         inside_subtest=
472         test "$#" > 0 ||
473             error "bug in the test script: test_json_nodes needs at least 1 parameter"
474
475         if ! test_skip "$test_subtest_name"
476         then
477             output=$(PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -B "$NOTMUCH_SRCDIR"/test/json_check_nodes.py "$@")
478                 if [ "$?" = 0 ]
479                 then
480                         test_ok_
481                 else
482                         test_failure_ "$output"
483                 fi
484         fi
485 }
486
487 NOTMUCH_NEW () {
488     notmuch new "${@}" | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
489 }
490
491 NOTMUCH_DUMP_TAGS () {
492     # this relies on the default format being batch-tag, otherwise some tests will break
493     notmuch dump --include=tags "${@}" | sed '/^#/d' | sort
494 }
495
496 notmuch_drop_mail_headers () {
497     $NOTMUCH_PYTHON -c '
498 import email, sys
499 msg = email.message_from_file(sys.stdin)
500 for hdr in sys.argv[1:]: del msg[hdr]
501 print(msg.as_string(False))
502 ' "$@"
503 }
504
505 notmuch_exception_sanitize () {
506     perl -pe 's/(A Xapian exception occurred at .*[.]cc?):([0-9]*)/\1:XXX/'
507 }
508
509 notmuch_search_sanitize () {
510     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
511 }
512
513 notmuch_search_files_sanitize () {
514     notmuch_dir_sanitize
515 }
516
517 notmuch_dir_sanitize () {
518     sed -e "s,$MAIL_DIR,MAIL_DIR," -e "s,${PWD},CWD,g" "$@"
519 }
520
521 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
522 notmuch_show_sanitize () {
523     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
524 }
525 notmuch_show_sanitize_all () {
526     sed \
527         -e 's| filename:.*| filename:XXXXX|' \
528         -e 's| id:[^ ]* | id:XXXXX |' | \
529         notmuch_date_sanitize
530 }
531
532 notmuch_json_show_sanitize () {
533     sed \
534         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
535         -e 's|"Date": "Fri, 05 Jan 2001 [^"]*0000"|"Date": "GENERATED_DATE"|g' \
536         -e 's|"filename": "signature.asc",||g' \
537         -e 's|"filename": \["/[^"]*"\],|"filename": \["YYYYY"\],|g' \
538         -e 's|"timestamp": 97.......|"timestamp": 42|g' \
539         -e 's|"content-length": [1-9][0-9]*|"content-length": "NONZERO"|g'
540 }
541
542 notmuch_emacs_error_sanitize () {
543     local command
544     command=$1
545     shift
546     for file in "$@"; do
547         echo "=== $file ==="
548         cat "$file"
549     done | sed \
550         -e 's/^\[.*\]$/[XXX]/' \
551         -e "s|^\(command: \)\{0,1\}/.*/$command|\1YYY/$command|"
552 }
553
554 notmuch_date_sanitize () {
555     sed \
556         -e 's/^Date: Fri, 05 Jan 2001 .*0000/Date: GENERATED_DATE/'
557 }
558
559 notmuch_uuid_sanitize () {
560     sed 's/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}/UUID/g'
561 }
562
563 notmuch_built_with_sanitize () {
564     sed 's/^built_with[.]\(.*\)=.*$/built_with.\1=something/'
565 }
566
567 notmuch_config_sanitize () {
568     notmuch_dir_sanitize | notmuch_built_with_sanitize
569 }
570
571 notmuch_show_part () {
572     awk '/^\014part}/{ f=0 }; { if (f) { print $0 } } /^\014part{ ID: '"$1"'/{ f=1 }'
573 }
574
575 # End of notmuch helper functions
576
577 # Use test_set_prereq to tell that a particular prerequisite is available.
578 #
579 # The prerequisite can later be checked for by using test_have_prereq.
580 #
581 # The single parameter is the prerequisite tag (a simple word, in all
582 # capital letters by convention).
583
584 test_set_prereq () {
585         satisfied="$satisfied$1 "
586 }
587 satisfied=" "
588
589 test_have_prereq () {
590         case $satisfied in
591         *" $1 "*)
592                 : yes, have it ;;
593         *)
594                 ! : nope ;;
595         esac
596 }
597
598 declare -A test_missing_external_prereq_
599 declare -A test_subtest_missing_external_prereq_
600
601 # declare prerequisite for the given external binary
602 test_declare_external_prereq () {
603         local binary
604         binary="$1"
605         test "$#" = 2 && name=$2 || name="$binary(1)"
606
607         if ! hash $binary 2>/dev/null; then
608                 test_missing_external_prereq_["${binary}"]=t
609                 eval "
610 $binary () {
611         test_subtest_missing_external_prereq_[\"${name}\"]=t
612         false
613 }"
614         fi
615 }
616
617 # Explicitly require external prerequisite.  Useful when binary is
618 # called indirectly (e.g. from emacs).
619 # Returns success if dependency is available, failure otherwise.
620 test_require_external_prereq () {
621         local binary
622         binary="$1"
623         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
624                 # dependency is missing, call the replacement function to note it
625                 eval "$binary"
626         else
627                 true
628         fi
629 }
630
631 # You are not expected to call test_ok_ and test_failure_ directly, use
632 # the text_expect_* functions instead.
633
634 test_ok_ () {
635         if test "$test_subtest_known_broken_" = "t"; then
636                 test_known_broken_ok_
637                 return
638         fi
639         test_success=$(($test_success + 1))
640         if test -n "$NOTMUCH_TEST_QUIET"; then
641                 return 0
642         fi
643         say_color pass "%-6s" "PASS"
644         echo " $test_subtest_name"
645 }
646
647 test_failure_ () {
648         print_test_description
649         if test "$test_subtest_known_broken_" = "t"; then
650                 test_known_broken_failure_ "$@"
651                 return
652         fi
653         test_failure=$(($test_failure + 1))
654         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
655         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
656         return 1
657 }
658
659 test_failure_message_ () {
660         say_color error "%-6s" "$1"
661         echo " $2"
662         shift 2
663         if [ "$#" != "0" ]; then
664                 echo "$@" | sed -e 's/^/        /'
665         fi
666         if test "$verbose" != "t"; then cat test.output; fi
667 }
668
669 test_known_broken_ok_ () {
670         test_reset_state_
671         test_fixed=$(($test_fixed+1))
672         say_color pass "%-6s" "FIXED"
673         echo " $test_subtest_name"
674 }
675
676 test_known_broken_failure_ () {
677         test_reset_state_
678         test_broken=$(($test_broken+1))
679         if [ -z "$NOTMUCH_TEST_QUIET" ]; then
680                 test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
681         else
682                 test_failure_message_ "BROKEN" "$test_subtest_name"
683         fi
684         return 1
685 }
686
687 test_debug () {
688         test "$debug" = "" || eval "$1"
689 }
690
691 test_run_ () {
692         test_cleanup=:
693         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
694         eval >&3 2>&4 "$1"
695         eval_ret=$?
696         eval >&3 2>&4 "$test_cleanup"
697         return 0
698 }
699
700 test_skip () {
701         test_count=$(($test_count+1))
702         to_skip=
703         for skp in $NOTMUCH_SKIP_TESTS
704         do
705                 case $this_test.$test_count in
706                 $skp)
707                         to_skip=t
708                         break
709                 esac
710                 case $this_test_bare.$test_count in
711                 $skp)
712                         to_skip=t
713                         break
714                 esac
715         done
716         case "$to_skip" in
717         t)
718                 test_report_skip_ "$@"
719                 ;;
720         *)
721                 test_check_missing_external_prereqs_ "$@"
722                 ;;
723         esac
724 }
725
726 test_check_missing_external_prereqs_ () {
727         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
728                 say_color skip >&1 "missing prerequisites: "
729                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
730                 test_report_skip_ "$@"
731         else
732                 false
733         fi
734 }
735
736 test_report_skip_ () {
737         test_reset_state_
738         say_color skip >&3 "skipping test:"
739         echo " $@" >&3
740         say_color skip "%-6s" "SKIP"
741         echo " $1"
742 }
743
744 test_subtest_known_broken () {
745         test_subtest_known_broken_=t
746 }
747
748 test_expect_success () {
749         exec 1>&6 2>&7          # Restore stdout and stderr
750         if [ -z "$inside_subtest" ]; then
751                 error "bug in the test script: test_expect_success without test_begin_subtest"
752         fi
753         inside_subtest=
754         test "$#" = 1 ||
755         error "bug in the test script: not 1 parameters to test_expect_success"
756
757         if ! test_skip "$test_subtest_name"
758         then
759                 test_run_ "$1"
760                 run_ret="$?"
761                 # test_run_ may update missing external prerequisites
762                 test_check_missing_external_prereqs_ "$test_subtest_name" ||
763                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
764                 then
765                         test_ok_
766                 else
767                         test_failure_ "$1"
768                 fi
769         fi
770 }
771
772 test_expect_code () {
773         exec 1>&6 2>&7          # Restore stdout and stderr
774         if [ -z "$inside_subtest" ]; then
775                 error "bug in the test script: test_expect_code without test_begin_subtest"
776         fi
777         inside_subtest=
778         test "$#" = 2 ||
779         error "bug in the test script: not 2 parameters to test_expect_code"
780
781         if ! test_skip "$test_subtest_name"
782         then
783                 test_run_ "$2"
784                 run_ret="$?"
785                 # test_run_ may update missing external prerequisites,
786                 test_check_missing_external_prereqs_ "$test_subtest_name" ||
787                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
788                 then
789                         test_ok_
790                 else
791                         test_failure_ "exit code $eval_ret, expected $1" "$2"
792                 fi
793         fi
794 }
795
796 # This is not among top-level (test_expect_success)
797 # but is a prefix that can be used in the test script, like:
798 #
799 #       test_expect_success 'complain and die' '
800 #           do something &&
801 #           do something else &&
802 #           test_must_fail git checkout ../outerspace
803 #       '
804 #
805 # Writing this as "! git checkout ../outerspace" is wrong, because
806 # the failure could be due to a segv.  We want a controlled failure.
807
808 test_must_fail () {
809         "$@"
810         test $? -gt 0 -a $? -le 129 -o $? -gt 192
811 }
812
813 # test_cmp is a helper function to compare actual and expected output.
814 # You can use it like:
815 #
816 #       test_expect_success 'foo works' '
817 #               echo expected >expected &&
818 #               foo >actual &&
819 #               test_cmp expected actual
820 #       '
821 #
822 # This could be written as either "cmp" or "diff -u", but:
823 # - cmp's output is not nearly as easy to read as diff -u
824 # - not all diff versions understand "-u"
825
826 test_cmp () {
827         $GIT_TEST_CMP "$@"
828 }
829
830 # This function can be used to schedule some commands to be run
831 # unconditionally at the end of the test to restore sanity:
832 #
833 #       test_expect_success 'test core.capslock' '
834 #               git config core.capslock true &&
835 #               test_when_finished "git config --unset core.capslock" &&
836 #               hello world
837 #       '
838 #
839 # That would be roughly equivalent to
840 #
841 #       test_expect_success 'test core.capslock' '
842 #               git config core.capslock true &&
843 #               hello world
844 #               git config --unset core.capslock
845 #       '
846 #
847 # except that the greeting and config --unset must both succeed for
848 # the test to pass.
849
850 test_when_finished () {
851         test_cleanup="{ $*
852                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
853 }
854
855 test_done () {
856         GIT_EXIT_OK=t
857         test_results_dir="$TEST_DIRECTORY/test-results"
858         mkdir -p "$test_results_dir"
859         test_results_path="$test_results_dir/$this_test"
860
861         echo "total $test_count" >> $test_results_path
862         echo "success $test_success" >> $test_results_path
863         echo "fixed $test_fixed" >> $test_results_path
864         echo "broken $test_broken" >> $test_results_path
865         echo "failed $test_failure" >> $test_results_path
866         echo "" >> $test_results_path
867
868         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
869
870         if [ "$test_failure" = "0" ]; then
871             if [ "$test_broken" = "0" ]; then
872                 rm -rf "$remove_tmp"
873             fi
874             exit 0
875         else
876             exit 1
877         fi
878 }
879
880 test_python () {
881     # Note: if there is need to print debug information from python program,
882     # use stdout = os.fdopen(6, 'w') or stderr = os.fdopen(7, 'w')
883     PYTHONPATH="$NOTMUCH_SRCDIR/bindings/python${PYTHONPATH:+:$PYTHONPATH}" \
884         $NOTMUCH_PYTHON -B - > OUTPUT
885 }
886
887 test_C () {
888     local exec_file test_file
889     exec_file="test${test_count}"
890     test_file="${exec_file}.c"
891     cat > ${test_file}
892     ${TEST_CC} ${TEST_CFLAGS} -I${NOTMUCH_SRCDIR}/test -I${NOTMUCH_SRCDIR}/lib -o ${exec_file} ${test_file} -L${NOTMUCH_BUILDDIR}/lib/ -lnotmuch -ltalloc
893     echo "== stdout ==" > OUTPUT.stdout
894     echo "== stderr ==" > OUTPUT.stderr
895     ./${exec_file} "$@" 1>>OUTPUT.stdout 2>>OUTPUT.stderr
896     notmuch_dir_sanitize OUTPUT.stdout OUTPUT.stderr | notmuch_exception_sanitize > OUTPUT
897 }
898
899 make_shim () {
900     local base_name test_file shim_file
901     base_name="$1"
902     test_file="${base_name}.c"
903     shim_file="${base_name}.so"
904     cat > ${test_file}
905     ${TEST_CC} ${TEST_CFLAGS} ${TEST_SHIM_CFLAGS} -I${NOTMUCH_SRCDIR}/test -I${NOTMUCH_SRCDIR}/lib -o ${shim_file} ${test_file} ${TEST_SHIM_LDFLAGS}
906 }
907
908 notmuch_with_shim () {
909     local base_name shim_file
910     base_name="$1"
911     shift
912     shim_file="${base_name}.so"
913     LD_PRELOAD=${LD_PRELOAD:+:$LD_PRELOAD}:./${shim_file} notmuch-shared "$@"
914 }
915
916 # Creates a script that counts how much time it is executed and calls
917 # notmuch.  $notmuch_counter_command is set to the path to the
918 # generated script.  Use notmuch_counter_value() function to get the
919 # current counter value.
920 notmuch_counter_reset () {
921         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
922         if [ ! -x "$notmuch_counter_command" ]; then
923                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
924                 cat >"$notmuch_counter_command" <<EOF || return
925 #!/bin/sh
926
927 read count < "$notmuch_counter_state_path"
928 echo \$((count + 1)) > "$notmuch_counter_state_path"
929
930 exec notmuch "\$@"
931 EOF
932                 chmod +x "$notmuch_counter_command" || return
933         fi
934
935         echo 0 > "$notmuch_counter_state_path"
936 }
937
938 # Returns the current notmuch counter value.
939 notmuch_counter_value () {
940         if [ -r "$notmuch_counter_state_path" ]; then
941                 read count < "$notmuch_counter_state_path"
942         else
943                 count=0
944         fi
945         echo $count
946 }
947
948 test_reset_state_ () {
949         test -z "$test_init_done_" && test_init_
950
951         test_subtest_known_broken_=
952         test_subtest_missing_external_prereq_=()
953 }
954
955 # called once before the first subtest
956 test_init_ () {
957         test_init_done_=t
958
959         # skip all tests if there were external prerequisites missing during init
960         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
961 }
962
963
964 # Where to run the tests
965 TEST_DIRECTORY=$NOTMUCH_BUILDDIR/test
966
967 . "$NOTMUCH_SRCDIR/test/test-lib-common.sh" || exit 1
968
969 # Use -P to resolve symlinks in our working directory so that the cwd
970 # in subprocesses like git equals our $PWD (for pathname comparisons).
971 cd -P "$TMP_DIRECTORY" || error "Cannot set up test environment"
972
973 if test "$verbose" = "t"
974 then
975         exec 4>&2 3>&1
976 else
977         exec 4>test.output 3>&4
978 fi
979
980 for skp in $NOTMUCH_SKIP_TESTS
981 do
982         to_skip=
983         for skp in $NOTMUCH_SKIP_TESTS
984         do
985                 case "$this_test" in
986                 $skp)
987                         to_skip=t
988                         break
989                 esac
990                 case "$this_test_bare" in
991                 $skp)
992                         to_skip=t
993                         break
994                 esac
995         done
996         case "$to_skip" in
997         t)
998                 say_color skip >&3 "skipping test $this_test altogether"
999                 say_color skip "skip all tests in $this_test"
1000                 test_done
1001         esac
1002 done
1003
1004 # Provide an implementation of the 'yes' utility
1005 yes () {
1006         if test $# = 0
1007         then
1008                 y=y
1009         else
1010                 y="$*"
1011         fi
1012
1013         while echo "$y"
1014         do
1015                 :
1016         done
1017 }
1018
1019 # Fix some commands on Windows
1020 case $(uname -s) in
1021 *MINGW*)
1022         # Windows has its own (incompatible) sort and find
1023         sort () {
1024                 /usr/bin/sort "$@"
1025         }
1026         find () {
1027                 /usr/bin/find "$@"
1028         }
1029         sum () {
1030                 md5sum "$@"
1031         }
1032         # git sees Windows-style pwd
1033         pwd () {
1034                 builtin pwd -W
1035         }
1036         # no POSIX permissions
1037         # backslashes in pathspec are converted to '/'
1038         # exec does not inherit the PID
1039         ;;
1040 *)
1041         test_set_prereq POSIXPERM
1042         test_set_prereq BSLASHPSPEC
1043         test_set_prereq EXECKEEPSPID
1044         ;;
1045 esac
1046
1047 test -z "$NO_PERL" && test_set_prereq PERL
1048 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1049
1050 # test whether the filesystem supports symbolic links
1051 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1052 rm -f y
1053
1054 # declare prerequisites for external binaries used in tests
1055 test_declare_external_prereq dtach
1056 test_declare_external_prereq emacs
1057 test_declare_external_prereq ${TEST_EMACSCLIENT}
1058 test_declare_external_prereq ${TEST_GDB}
1059 test_declare_external_prereq gpg
1060 test_declare_external_prereq openssl
1061 test_declare_external_prereq gpgsm
1062 test_declare_external_prereq ${NOTMUCH_PYTHON}
1063 test_declare_external_prereq xapian-metadata
1064 test_declare_external_prereq xapian-delve