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