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