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