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