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