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