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