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