]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: suppress diff for broken test without V=1
[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         if [ "$#" != "0" ]; then
870                 echo "$@" | sed -e 's/^/        /'
871         fi
872         if test "$verbose" != "t"; then cat test.output; fi
873 }
874
875 test_known_broken_ok_ () {
876         test_reset_state_
877         test_fixed=$(($test_fixed+1))
878         say_color pass "%-6s" "FIXED"
879         echo " $test_subtest_name"
880 }
881
882 test_known_broken_failure_ () {
883         test_reset_state_
884         test_broken=$(($test_broken+1))
885         if [ -z "$NOTMUCH_TEST_QUIET" ]; then
886                 test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
887         else
888                 test_failure_message_ "BROKEN" "$test_subtest_name"
889         fi
890         return 1
891 }
892
893 test_debug () {
894         test "$debug" = "" || eval "$1"
895 }
896
897 test_run_ () {
898         test_cleanup=:
899         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
900         eval >&3 2>&4 "$1"
901         eval_ret=$?
902         eval >&3 2>&4 "$test_cleanup"
903         return 0
904 }
905
906 test_skip () {
907         test_count=$(($test_count+1))
908         to_skip=
909         for skp in $NOTMUCH_SKIP_TESTS
910         do
911                 case $this_test.$test_count in
912                 $skp)
913                         to_skip=t
914                         break
915                 esac
916                 case $this_test_bare.$test_count in
917                 $skp)
918                         to_skip=t
919                         break
920                 esac
921         done
922         if test -z "$to_skip" && test -n "$prereq" &&
923            ! test_have_prereq "$prereq"
924         then
925                 to_skip=t
926         fi
927         case "$to_skip" in
928         t)
929                 test_report_skip_ "$@"
930                 ;;
931         *)
932                 test_check_missing_external_prereqs_ "$@"
933                 ;;
934         esac
935 }
936
937 test_check_missing_external_prereqs_ () {
938         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
939                 say_color skip >&1 "missing prerequisites: "
940                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
941                 test_report_skip_ "$@"
942         else
943                 false
944         fi
945 }
946
947 test_report_skip_ () {
948         test_reset_state_
949         say_color skip >&3 "skipping test:"
950         echo " $@" >&3
951         say_color skip "%-6s" "SKIP"
952         echo " $1"
953 }
954
955 test_subtest_known_broken () {
956         test_subtest_known_broken_=t
957 }
958
959 test_expect_success () {
960         test "$#" = 3 && { prereq=$1; shift; } || prereq=
961         test "$#" = 2 ||
962         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
963         test_subtest_name="$1"
964         test_reset_state_
965         if ! test_skip "$@"
966         then
967                 test_run_ "$2"
968                 run_ret="$?"
969                 # test_run_ may update missing external prerequisites
970                 test_check_missing_external_prereqs_ "$@" ||
971                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
972                 then
973                         test_ok_
974                 else
975                         test_failure_ "$2"
976                 fi
977         fi
978 }
979
980 test_expect_code () {
981         test "$#" = 4 && { prereq=$1; shift; } || prereq=
982         test "$#" = 3 ||
983         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
984         test_subtest_name="$2"
985         test_reset_state_
986         if ! test_skip "$@"
987         then
988                 test_run_ "$3"
989                 run_ret="$?"
990                 # test_run_ may update missing external prerequisites,
991                 test_check_missing_external_prereqs_ "$@" ||
992                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
993                 then
994                         test_ok_
995                 else
996                         test_failure_ "exit code $eval_ret, expected $1" "$3"
997                 fi
998         fi
999 }
1000
1001 # test_external runs external test scripts that provide continuous
1002 # test output about their progress, and succeeds/fails on
1003 # zero/non-zero exit code.  It outputs the test output on stdout even
1004 # in non-verbose mode, and announces the external script with "* run
1005 # <n>: ..." before running it.  When providing relative paths, keep in
1006 # mind that all scripts run in "trash directory".
1007 # Usage: test_external description command arguments...
1008 # Example: test_external 'Perl API' perl ../path/to/test.pl
1009 test_external () {
1010         test "$#" = 4 && { prereq=$1; shift; } || prereq=
1011         test "$#" = 3 ||
1012         error >&6 "bug in the test script: not 3 or 4 parameters to test_external"
1013         test_subtest_name="$1"
1014         shift
1015         test_reset_state_
1016         if ! test_skip "$test_subtest_name" "$@"
1017         then
1018                 # Announce the script to reduce confusion about the
1019                 # test output that follows.
1020                 say_color "" " run $test_count: $descr ($*)"
1021                 # Run command; redirect its stderr to &4 as in
1022                 # test_run_, but keep its stdout on our stdout even in
1023                 # non-verbose mode.
1024                 "$@" 2>&4
1025                 if [ "$?" = 0 ]
1026                 then
1027                         test_ok_
1028                 else
1029                         test_failure_ "$@"
1030                 fi
1031         fi
1032 }
1033
1034 # Like test_external, but in addition tests that the command generated
1035 # no output on stderr.
1036 test_external_without_stderr () {
1037         # The temporary file has no (and must have no) security
1038         # implications.
1039         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
1040         stderr="$tmp/git-external-stderr.$$.tmp"
1041         test_external "$@" 4> "$stderr"
1042         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
1043         test_subtest_name="no stderr: $1"
1044         shift
1045         if [ ! -s "$stderr" ]; then
1046                 rm "$stderr"
1047                 test_ok_
1048         else
1049                 if [ "$verbose" = t ]; then
1050                         output=`echo; echo Stderr is:; cat "$stderr"`
1051                 else
1052                         output=
1053                 fi
1054                 # rm first in case test_failure exits.
1055                 rm "$stderr"
1056                 test_failure_ "$@" "$output"
1057         fi
1058 }
1059
1060 # This is not among top-level (test_expect_success)
1061 # but is a prefix that can be used in the test script, like:
1062 #
1063 #       test_expect_success 'complain and die' '
1064 #           do something &&
1065 #           do something else &&
1066 #           test_must_fail git checkout ../outerspace
1067 #       '
1068 #
1069 # Writing this as "! git checkout ../outerspace" is wrong, because
1070 # the failure could be due to a segv.  We want a controlled failure.
1071
1072 test_must_fail () {
1073         "$@"
1074         test $? -gt 0 -a $? -le 129 -o $? -gt 192
1075 }
1076
1077 # test_cmp is a helper function to compare actual and expected output.
1078 # You can use it like:
1079 #
1080 #       test_expect_success 'foo works' '
1081 #               echo expected >expected &&
1082 #               foo >actual &&
1083 #               test_cmp expected actual
1084 #       '
1085 #
1086 # This could be written as either "cmp" or "diff -u", but:
1087 # - cmp's output is not nearly as easy to read as diff -u
1088 # - not all diff versions understand "-u"
1089
1090 test_cmp() {
1091         $GIT_TEST_CMP "$@"
1092 }
1093
1094 # This function can be used to schedule some commands to be run
1095 # unconditionally at the end of the test to restore sanity:
1096 #
1097 #       test_expect_success 'test core.capslock' '
1098 #               git config core.capslock true &&
1099 #               test_when_finished "git config --unset core.capslock" &&
1100 #               hello world
1101 #       '
1102 #
1103 # That would be roughly equivalent to
1104 #
1105 #       test_expect_success 'test core.capslock' '
1106 #               git config core.capslock true &&
1107 #               hello world
1108 #               git config --unset core.capslock
1109 #       '
1110 #
1111 # except that the greeting and config --unset must both succeed for
1112 # the test to pass.
1113
1114 test_when_finished () {
1115         test_cleanup="{ $*
1116                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
1117 }
1118
1119 test_done () {
1120         GIT_EXIT_OK=t
1121         test_results_dir="$TEST_DIRECTORY/test-results"
1122         mkdir -p "$test_results_dir"
1123         test_results_path="$test_results_dir/$this_test"
1124
1125         echo "total $test_count" >> $test_results_path
1126         echo "success $test_success" >> $test_results_path
1127         echo "fixed $test_fixed" >> $test_results_path
1128         echo "broken $test_broken" >> $test_results_path
1129         echo "failed $test_failure" >> $test_results_path
1130         echo "" >> $test_results_path
1131
1132         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
1133
1134         if [ "$test_failure" = "0" ]; then
1135             if [ "$test_broken" = "0" ]; then
1136                 rm -rf "$remove_tmp"
1137             fi
1138             exit 0
1139         else
1140             exit 1
1141         fi
1142 }
1143
1144 emacs_generate_script () {
1145         # Construct a little test script here for the benefit of the user,
1146         # (who can easily run "run_emacs" to get the same emacs environment
1147         # for investigating any failures).
1148         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
1149 #!/bin/sh
1150 export PATH=$PATH
1151 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
1152
1153 # Here's what we are using here:
1154 #
1155 # --quick              Use minimal customization. This implies --no-init-file,
1156 #                      --no-site-file and (emacs 24) --no-site-lisp
1157 #
1158 # --directory           Ensure that the local elisp sources are found
1159 #
1160 # --load                Force loading of notmuch.el and test-lib.el
1161
1162 exec ${TEST_EMACS} --quick \
1163         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
1164         --directory "$TEST_DIRECTORY" --load test-lib.el \
1165         "\$@"
1166 EOF
1167         chmod a+x "$TMP_DIRECTORY/run_emacs"
1168 }
1169
1170 test_emacs () {
1171         # test dependencies beforehand to avoid the waiting loop below
1172         missing_dependencies=
1173         test_require_external_prereq dtach || missing_dependencies=1
1174         test_require_external_prereq emacs || missing_dependencies=1
1175         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
1176         test -z "$missing_dependencies" || return
1177
1178         if [ -z "$EMACS_SERVER" ]; then
1179                 emacs_tests="${this_test_bare}.el"
1180                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
1181                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
1182                 else
1183                         load_emacs_tests=
1184                 fi
1185                 server_name="notmuch-test-suite-$$"
1186                 # start a detached session with an emacs server
1187                 # user's TERM (or 'vt100' in case user's TERM is known dumb
1188                 # or unknown) is given to dtach which assumes a minimally
1189                 # VT100-compatible terminal -- and emacs inherits that
1190                 TERM=$SMART_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
1191                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
1192                                 --no-window-system \
1193                                 $load_emacs_tests \
1194                                 --eval '(setq server-name \"$server_name\")' \
1195                                 --eval '(server-start)' \
1196                                 --eval '(orphan-watchdog $$)'" || return
1197                 EMACS_SERVER="$server_name"
1198                 # wait until the emacs server is up
1199                 until test_emacs '()' >/dev/null 2>/dev/null; do
1200                         sleep 1
1201                 done
1202         fi
1203
1204         # Clear test-output output file.  Most Emacs tests end with a
1205         # call to (test-output).  If the test code fails with an
1206         # exception before this call, the output file won't get
1207         # updated.  Since we don't want to compare against an output
1208         # file from another test, so start out with an empty file.
1209         rm -f OUTPUT
1210         touch OUTPUT
1211
1212         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(notmuch-test-progn $@)"
1213 }
1214
1215 test_python() {
1216     # Note: if there is need to print debug information from python program,
1217     # use stdout = os.fdopen(6, 'w') or stderr = os.fdopen(7, 'w')
1218     PYTHONPATH="$TEST_DIRECTORY/../bindings/python${PYTHONPATH:+:$PYTHONPATH}" \
1219         $NOTMUCH_PYTHON -B - > OUTPUT
1220 }
1221
1222 test_ruby() {
1223     MAIL_DIR=$MAIL_DIR ruby -I $TEST_DIRECTORY/../bindings/ruby> OUTPUT
1224 }
1225
1226 test_C () {
1227     exec_file="test${test_count}"
1228     test_file="${exec_file}.c"
1229     cat > ${test_file}
1230     ${TEST_CC} ${TEST_CFLAGS} -I${TEST_DIRECTORY} -I${TEST_DIRECTORY}/../lib -o ${exec_file} ${test_file} -L${TEST_DIRECTORY}/../lib/ -lnotmuch -ltalloc
1231     echo "== stdout ==" > OUTPUT.stdout
1232     echo "== stderr ==" > OUTPUT.stderr
1233     ./${exec_file} "$@" 1>>OUTPUT.stdout 2>>OUTPUT.stderr
1234     notmuch_dir_sanitize OUTPUT.stdout OUTPUT.stderr > OUTPUT
1235 }
1236
1237
1238 # Creates a script that counts how much time it is executed and calls
1239 # notmuch.  $notmuch_counter_command is set to the path to the
1240 # generated script.  Use notmuch_counter_value() function to get the
1241 # current counter value.
1242 notmuch_counter_reset () {
1243         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
1244         if [ ! -x "$notmuch_counter_command" ]; then
1245                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
1246                 cat >"$notmuch_counter_command" <<EOF || return
1247 #!/bin/sh
1248
1249 read count < "$notmuch_counter_state_path"
1250 echo \$((count + 1)) > "$notmuch_counter_state_path"
1251
1252 exec notmuch "\$@"
1253 EOF
1254                 chmod +x "$notmuch_counter_command" || return
1255         fi
1256
1257         echo 0 > "$notmuch_counter_state_path"
1258 }
1259
1260 # Returns the current notmuch counter value.
1261 notmuch_counter_value () {
1262         if [ -r "$notmuch_counter_state_path" ]; then
1263                 read count < "$notmuch_counter_state_path"
1264         else
1265                 count=0
1266         fi
1267         echo $count
1268 }
1269
1270 test_reset_state_ () {
1271         test -z "$test_init_done_" && test_init_
1272
1273         test_subtest_known_broken_=
1274         test_subtest_missing_external_prereq_=()
1275 }
1276
1277 # called once before the first subtest
1278 test_init_ () {
1279         test_init_done_=t
1280
1281         # skip all tests if there were external prerequisites missing during init
1282         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1283 }
1284
1285
1286 . ./test-lib-common.sh || exit 1
1287
1288 emacs_generate_script
1289
1290
1291 # Use -P to resolve symlinks in our working directory so that the cwd
1292 # in subprocesses like git equals our $PWD (for pathname comparisons).
1293 cd -P "$test" || error "Cannot set up test environment"
1294
1295 if test "$verbose" = "t"
1296 then
1297         exec 4>&2 3>&1
1298 else
1299         exec 4>test.output 3>&4
1300 fi
1301
1302 for skp in $NOTMUCH_SKIP_TESTS
1303 do
1304         to_skip=
1305         for skp in $NOTMUCH_SKIP_TESTS
1306         do
1307                 case "$this_test" in
1308                 $skp)
1309                         to_skip=t
1310                         break
1311                 esac
1312                 case "$this_test_bare" in
1313                 $skp)
1314                         to_skip=t
1315                         break
1316                 esac
1317         done
1318         case "$to_skip" in
1319         t)
1320                 say_color skip >&3 "skipping test $this_test altogether"
1321                 say_color skip "skip all tests in $this_test"
1322                 test_done
1323         esac
1324 done
1325
1326 # Provide an implementation of the 'yes' utility
1327 yes () {
1328         if test $# = 0
1329         then
1330                 y=y
1331         else
1332                 y="$*"
1333         fi
1334
1335         while echo "$y"
1336         do
1337                 :
1338         done
1339 }
1340
1341 # Fix some commands on Windows
1342 case $(uname -s) in
1343 *MINGW*)
1344         # Windows has its own (incompatible) sort and find
1345         sort () {
1346                 /usr/bin/sort "$@"
1347         }
1348         find () {
1349                 /usr/bin/find "$@"
1350         }
1351         sum () {
1352                 md5sum "$@"
1353         }
1354         # git sees Windows-style pwd
1355         pwd () {
1356                 builtin pwd -W
1357         }
1358         # no POSIX permissions
1359         # backslashes in pathspec are converted to '/'
1360         # exec does not inherit the PID
1361         ;;
1362 *)
1363         test_set_prereq POSIXPERM
1364         test_set_prereq BSLASHPSPEC
1365         test_set_prereq EXECKEEPSPID
1366         ;;
1367 esac
1368
1369 test -z "$NO_PERL" && test_set_prereq PERL
1370 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1371
1372 # test whether the filesystem supports symbolic links
1373 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1374 rm -f y
1375
1376 # convert variable from configure to more convenient form
1377 case "$NOTMUCH_DEFAULT_XAPIAN_BACKEND" in
1378     glass)
1379         db_ending=glass
1380     ;;
1381     chert)
1382         db_ending=DB
1383     ;;
1384     *)
1385         error "Unknown Xapian backend $NOTMUCH_DEFAULT_XAPIAN_BACKEND"
1386 esac
1387 # declare prerequisites for external binaries used in tests
1388 test_declare_external_prereq dtach
1389 test_declare_external_prereq emacs
1390 test_declare_external_prereq ${TEST_EMACSCLIENT}
1391 test_declare_external_prereq ${TEST_GDB}
1392 test_declare_external_prereq gpg
1393 test_declare_external_prereq openssl
1394 test_declare_external_prereq gpgsm
1395 test_declare_external_prereq ${NOTMUCH_PYTHON}