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