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