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