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