]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
CLI: add optional config data to dump output.
[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_DUMP_TAGS ()
678 {
679     # this relies on the default format being batch-tag, otherwise some tests will break
680     notmuch dump --include=tags "${@}" | sed '/^#/d' | sort
681 }
682
683 notmuch_search_sanitize ()
684 {
685     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
686 }
687
688 notmuch_search_files_sanitize ()
689 {
690     notmuch_dir_sanitize
691 }
692
693 notmuch_dir_sanitize ()
694 {
695     sed -e "s,$MAIL_DIR,MAIL_DIR," -e "s,${PWD},CWD,g" "$@"
696 }
697
698 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
699 notmuch_show_sanitize ()
700 {
701     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
702 }
703 notmuch_show_sanitize_all ()
704 {
705     sed \
706         -e 's| filename:.*| filename:XXXXX|' \
707         -e 's| id:[^ ]* | id:XXXXX |' | \
708         notmuch_date_sanitize
709 }
710
711 notmuch_json_show_sanitize ()
712 {
713     sed \
714         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
715         -e 's|"Date": "Fri, 05 Jan 2001 [^"]*0000"|"Date": "GENERATED_DATE"|g' \
716         -e 's|"filename": "signature.asc",||g' \
717         -e 's|"filename": "/[^"]*",|"filename": "YYYYY",|g' \
718         -e 's|"timestamp": 97.......|"timestamp": 42|g'
719 }
720
721 notmuch_emacs_error_sanitize ()
722 {
723     local command=$1
724     shift
725     for file in "$@"; do
726         echo "=== $file ==="
727         cat "$file"
728     done | sed  \
729         -e 's/^\[.*\]$/[XXX]/' \
730         -e "s|^\(command: \)\{0,1\}/.*/$command|\1YYY/$command|"
731 }
732
733 notmuch_date_sanitize ()
734 {
735     sed \
736         -e 's/^Date: Fri, 05 Jan 2001 .*0000/Date: GENERATED_DATE/'
737 }
738
739 notmuch_uuid_sanitize ()
740 {
741     sed 's/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}/UUID/g'
742 }
743
744 notmuch_built_with_sanitize ()
745 {
746     sed 's/^built_with[.]\(.*\)=.*$/built_with.\1=something/'
747 }
748
749 # End of notmuch helper functions
750
751 # Use test_set_prereq to tell that a particular prerequisite is available.
752 # The prerequisite can later be checked for in two ways:
753 #
754 # - Explicitly using test_have_prereq.
755 #
756 # - Implicitly by specifying the prerequisite tag in the calls to
757 #   test_expect_{success,failure,code}.
758 #
759 # The single parameter is the prerequisite tag (a simple word, in all
760 # capital letters by convention).
761
762 test_set_prereq () {
763         satisfied="$satisfied$1 "
764 }
765 satisfied=" "
766
767 test_have_prereq () {
768         case $satisfied in
769         *" $1 "*)
770                 : yes, have it ;;
771         *)
772                 ! : nope ;;
773         esac
774 }
775
776 declare -A test_missing_external_prereq_
777 declare -A test_subtest_missing_external_prereq_
778
779 # declare prerequisite for the given external binary
780 test_declare_external_prereq () {
781         binary="$1"
782         test "$#" = 2 && name=$2 || name="$binary(1)"
783
784         if ! hash $binary 2>/dev/null; then
785                 test_missing_external_prereq_["${binary}"]=t
786                 eval "
787 $binary () {
788         test_subtest_missing_external_prereq_[\"${name}\"]=t
789         false
790 }"
791         fi
792 }
793
794 # Explicitly require external prerequisite.  Useful when binary is
795 # called indirectly (e.g. from emacs).
796 # Returns success if dependency is available, failure otherwise.
797 test_require_external_prereq () {
798         binary="$1"
799         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
800                 # dependency is missing, call the replacement function to note it
801                 eval "$binary"
802         else
803                 true
804         fi
805 }
806
807 # You are not expected to call test_ok_ and test_failure_ directly, use
808 # the text_expect_* functions instead.
809
810 test_ok_ () {
811         if test "$test_subtest_known_broken_" = "t"; then
812                 test_known_broken_ok_
813                 return
814         fi
815         test_success=$(($test_success + 1))
816         if test -n "$NOTMUCH_TEST_QUIET"; then
817                 return 0
818         fi
819         say_color pass "%-6s" "PASS"
820         echo " $test_subtest_name"
821 }
822
823 test_failure_ () {
824         if test "$test_subtest_known_broken_" = "t"; then
825                 test_known_broken_failure_ "$@"
826                 return
827         fi
828         test_failure=$(($test_failure + 1))
829         print_test_description
830         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
831         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
832         return 1
833 }
834
835 test_failure_message_ () {
836         say_color error "%-6s" "$1"
837         echo " $2"
838         shift 2
839         echo "$@" | sed -e 's/^/        /'
840         if test "$verbose" != "t"; then cat test.output; fi
841 }
842
843 test_known_broken_ok_ () {
844         test_reset_state_
845         test_fixed=$(($test_fixed+1))
846         say_color pass "%-6s" "FIXED"
847         echo " $test_subtest_name"
848 }
849
850 test_known_broken_failure_ () {
851         test_reset_state_
852         test_broken=$(($test_broken+1))
853         test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
854         return 1
855 }
856
857 test_debug () {
858         test "$debug" = "" || eval "$1"
859 }
860
861 test_run_ () {
862         test_cleanup=:
863         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
864         eval >&3 2>&4 "$1"
865         eval_ret=$?
866         eval >&3 2>&4 "$test_cleanup"
867         return 0
868 }
869
870 test_skip () {
871         test_count=$(($test_count+1))
872         to_skip=
873         for skp in $NOTMUCH_SKIP_TESTS
874         do
875                 case $this_test.$test_count in
876                 $skp)
877                         to_skip=t
878                         break
879                 esac
880                 case $this_test_bare.$test_count in
881                 $skp)
882                         to_skip=t
883                         break
884                 esac
885         done
886         if test -z "$to_skip" && test -n "$prereq" &&
887            ! test_have_prereq "$prereq"
888         then
889                 to_skip=t
890         fi
891         case "$to_skip" in
892         t)
893                 test_report_skip_ "$@"
894                 ;;
895         *)
896                 test_check_missing_external_prereqs_ "$@"
897                 ;;
898         esac
899 }
900
901 test_check_missing_external_prereqs_ () {
902         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
903                 say_color skip >&1 "missing prerequisites: "
904                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
905                 test_report_skip_ "$@"
906         else
907                 false
908         fi
909 }
910
911 test_report_skip_ () {
912         test_reset_state_
913         say_color skip >&3 "skipping test:"
914         echo " $@" >&3
915         say_color skip "%-6s" "SKIP"
916         echo " $1"
917 }
918
919 test_subtest_known_broken () {
920         test_subtest_known_broken_=t
921 }
922
923 test_expect_success () {
924         test "$#" = 3 && { prereq=$1; shift; } || prereq=
925         test "$#" = 2 ||
926         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
927         test_subtest_name="$1"
928         test_reset_state_
929         if ! test_skip "$@"
930         then
931                 test_run_ "$2"
932                 run_ret="$?"
933                 # test_run_ may update missing external prerequisites
934                 test_check_missing_external_prereqs_ "$@" ||
935                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
936                 then
937                         test_ok_
938                 else
939                         test_failure_ "$2"
940                 fi
941         fi
942 }
943
944 test_expect_code () {
945         test "$#" = 4 && { prereq=$1; shift; } || prereq=
946         test "$#" = 3 ||
947         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
948         test_subtest_name="$2"
949         test_reset_state_
950         if ! test_skip "$@"
951         then
952                 test_run_ "$3"
953                 run_ret="$?"
954                 # test_run_ may update missing external prerequisites,
955                 test_check_missing_external_prereqs_ "$@" ||
956                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
957                 then
958                         test_ok_
959                 else
960                         test_failure_ "exit code $eval_ret, expected $1" "$3"
961                 fi
962         fi
963 }
964
965 # test_external runs external test scripts that provide continuous
966 # test output about their progress, and succeeds/fails on
967 # zero/non-zero exit code.  It outputs the test output on stdout even
968 # in non-verbose mode, and announces the external script with "* run
969 # <n>: ..." before running it.  When providing relative paths, keep in
970 # mind that all scripts run in "trash directory".
971 # Usage: test_external description command arguments...
972 # Example: test_external 'Perl API' perl ../path/to/test.pl
973 test_external () {
974         test "$#" = 4 && { prereq=$1; shift; } || prereq=
975         test "$#" = 3 ||
976         error >&6 "bug in the test script: not 3 or 4 parameters to test_external"
977         test_subtest_name="$1"
978         shift
979         test_reset_state_
980         if ! test_skip "$test_subtest_name" "$@"
981         then
982                 # Announce the script to reduce confusion about the
983                 # test output that follows.
984                 say_color "" " run $test_count: $descr ($*)"
985                 # Run command; redirect its stderr to &4 as in
986                 # test_run_, but keep its stdout on our stdout even in
987                 # non-verbose mode.
988                 "$@" 2>&4
989                 if [ "$?" = 0 ]
990                 then
991                         test_ok_
992                 else
993                         test_failure_ "$@"
994                 fi
995         fi
996 }
997
998 # Like test_external, but in addition tests that the command generated
999 # no output on stderr.
1000 test_external_without_stderr () {
1001         # The temporary file has no (and must have no) security
1002         # implications.
1003         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
1004         stderr="$tmp/git-external-stderr.$$.tmp"
1005         test_external "$@" 4> "$stderr"
1006         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
1007         test_subtest_name="no stderr: $1"
1008         shift
1009         if [ ! -s "$stderr" ]; then
1010                 rm "$stderr"
1011                 test_ok_
1012         else
1013                 if [ "$verbose" = t ]; then
1014                         output=`echo; echo Stderr is:; cat "$stderr"`
1015                 else
1016                         output=
1017                 fi
1018                 # rm first in case test_failure exits.
1019                 rm "$stderr"
1020                 test_failure_ "$@" "$output"
1021         fi
1022 }
1023
1024 # This is not among top-level (test_expect_success)
1025 # but is a prefix that can be used in the test script, like:
1026 #
1027 #       test_expect_success 'complain and die' '
1028 #           do something &&
1029 #           do something else &&
1030 #           test_must_fail git checkout ../outerspace
1031 #       '
1032 #
1033 # Writing this as "! git checkout ../outerspace" is wrong, because
1034 # the failure could be due to a segv.  We want a controlled failure.
1035
1036 test_must_fail () {
1037         "$@"
1038         test $? -gt 0 -a $? -le 129 -o $? -gt 192
1039 }
1040
1041 # test_cmp is a helper function to compare actual and expected output.
1042 # You can use it like:
1043 #
1044 #       test_expect_success 'foo works' '
1045 #               echo expected >expected &&
1046 #               foo >actual &&
1047 #               test_cmp expected actual
1048 #       '
1049 #
1050 # This could be written as either "cmp" or "diff -u", but:
1051 # - cmp's output is not nearly as easy to read as diff -u
1052 # - not all diff versions understand "-u"
1053
1054 test_cmp() {
1055         $GIT_TEST_CMP "$@"
1056 }
1057
1058 # This function can be used to schedule some commands to be run
1059 # unconditionally at the end of the test to restore sanity:
1060 #
1061 #       test_expect_success 'test core.capslock' '
1062 #               git config core.capslock true &&
1063 #               test_when_finished "git config --unset core.capslock" &&
1064 #               hello world
1065 #       '
1066 #
1067 # That would be roughly equivalent to
1068 #
1069 #       test_expect_success 'test core.capslock' '
1070 #               git config core.capslock true &&
1071 #               hello world
1072 #               git config --unset core.capslock
1073 #       '
1074 #
1075 # except that the greeting and config --unset must both succeed for
1076 # the test to pass.
1077
1078 test_when_finished () {
1079         test_cleanup="{ $*
1080                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
1081 }
1082
1083 test_done () {
1084         GIT_EXIT_OK=t
1085         test_results_dir="$TEST_DIRECTORY/test-results"
1086         mkdir -p "$test_results_dir"
1087         test_results_path="$test_results_dir/$this_test"
1088
1089         echo "total $test_count" >> $test_results_path
1090         echo "success $test_success" >> $test_results_path
1091         echo "fixed $test_fixed" >> $test_results_path
1092         echo "broken $test_broken" >> $test_results_path
1093         echo "failed $test_failure" >> $test_results_path
1094         echo "" >> $test_results_path
1095
1096         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
1097
1098         if [ "$test_failure" = "0" ]; then
1099             if [ "$test_broken" = "0" ]; then
1100                 rm -rf "$remove_tmp"
1101             fi
1102             exit 0
1103         else
1104             exit 1
1105         fi
1106 }
1107
1108 emacs_generate_script () {
1109         # Construct a little test script here for the benefit of the user,
1110         # (who can easily run "run_emacs" to get the same emacs environment
1111         # for investigating any failures).
1112         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
1113 #!/bin/sh
1114 export PATH=$PATH
1115 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
1116
1117 # Here's what we are using here:
1118 #
1119 # --quick              Use minimal customization. This implies --no-init-file,
1120 #                      --no-site-file and (emacs 24) --no-site-lisp
1121 #
1122 # --directory           Ensure that the local elisp sources are found
1123 #
1124 # --load                Force loading of notmuch.el and test-lib.el
1125
1126 exec ${TEST_EMACS} --quick \
1127         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
1128         --directory "$TEST_DIRECTORY" --load test-lib.el \
1129         "\$@"
1130 EOF
1131         chmod a+x "$TMP_DIRECTORY/run_emacs"
1132 }
1133
1134 test_emacs () {
1135         # test dependencies beforehand to avoid the waiting loop below
1136         missing_dependencies=
1137         test_require_external_prereq dtach || missing_dependencies=1
1138         test_require_external_prereq emacs || missing_dependencies=1
1139         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
1140         test -z "$missing_dependencies" || return
1141
1142         if [ -z "$EMACS_SERVER" ]; then
1143                 emacs_tests="${this_test_bare}.el"
1144                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
1145                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
1146                 else
1147                         load_emacs_tests=
1148                 fi
1149                 server_name="notmuch-test-suite-$$"
1150                 # start a detached session with an emacs server
1151                 # user's TERM (or 'vt100' in case user's TERM is unset, empty
1152                 # or 'dumb') is given to dtach which assumes a minimally
1153                 # VT100-compatible terminal -- and emacs inherits that
1154                 TERM=$DTACH_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
1155                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
1156                                 --no-window-system \
1157                                 $load_emacs_tests \
1158                                 --eval '(setq server-name \"$server_name\")' \
1159                                 --eval '(server-start)' \
1160                                 --eval '(orphan-watchdog $$)'" || return
1161                 EMACS_SERVER="$server_name"
1162                 # wait until the emacs server is up
1163                 until test_emacs '()' >/dev/null 2>/dev/null; do
1164                         sleep 1
1165                 done
1166         fi
1167
1168         # Clear test-output output file.  Most Emacs tests end with a
1169         # call to (test-output).  If the test code fails with an
1170         # exception before this call, the output file won't get
1171         # updated.  Since we don't want to compare against an output
1172         # file from another test, so start out with an empty file.
1173         rm -f OUTPUT
1174         touch OUTPUT
1175
1176         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(notmuch-test-progn $@)"
1177 }
1178
1179 test_python() {
1180         export LD_LIBRARY_PATH=$TEST_DIRECTORY/../lib
1181         export PYTHONPATH=$TEST_DIRECTORY/../bindings/python
1182
1183         (echo "import sys; _orig_stdout=sys.stdout; sys.stdout=open('OUTPUT', 'w')"; cat) \
1184                 | $NOTMUCH_PYTHON -
1185 }
1186
1187 test_ruby() {
1188     export LD_LIBRARY_PATH=$TEST_DIRECTORY/../lib
1189     MAIL_DIR=$MAIL_DIR ruby -I $TEST_DIRECTORY/../bindings/ruby> OUTPUT
1190 }
1191
1192 test_C () {
1193     exec_file="test${test_count}"
1194     test_file="${exec_file}.c"
1195     cat > ${test_file}
1196     export LD_LIBRARY_PATH=${TEST_DIRECTORY}/../lib
1197     ${TEST_CC} ${TEST_CFLAGS} -I${TEST_DIRECTORY}/../lib -o ${exec_file} ${test_file} -L${TEST_DIRECTORY}/../lib/ -lnotmuch -ltalloc
1198     echo "== stdout ==" > OUTPUT.stdout
1199     echo "== stderr ==" > OUTPUT.stderr
1200     ./${exec_file} "$@" 1>>OUTPUT.stdout 2>>OUTPUT.stderr
1201     notmuch_dir_sanitize OUTPUT.stdout OUTPUT.stderr > OUTPUT
1202 }
1203
1204
1205 # Creates a script that counts how much time it is executed and calls
1206 # notmuch.  $notmuch_counter_command is set to the path to the
1207 # generated script.  Use notmuch_counter_value() function to get the
1208 # current counter value.
1209 notmuch_counter_reset () {
1210         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
1211         if [ ! -x "$notmuch_counter_command" ]; then
1212                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
1213                 cat >"$notmuch_counter_command" <<EOF || return
1214 #!/bin/sh
1215
1216 read count < "$notmuch_counter_state_path"
1217 echo \$((count + 1)) > "$notmuch_counter_state_path"
1218
1219 exec notmuch "\$@"
1220 EOF
1221                 chmod +x "$notmuch_counter_command" || return
1222         fi
1223
1224         echo 0 > "$notmuch_counter_state_path"
1225 }
1226
1227 # Returns the current notmuch counter value.
1228 notmuch_counter_value () {
1229         if [ -r "$notmuch_counter_state_path" ]; then
1230                 read count < "$notmuch_counter_state_path"
1231         else
1232                 count=0
1233         fi
1234         echo $count
1235 }
1236
1237 test_reset_state_ () {
1238         test -z "$test_init_done_" && test_init_
1239
1240         test_subtest_known_broken_=
1241         test_subtest_missing_external_prereq_=()
1242 }
1243
1244 # called once before the first subtest
1245 test_init_ () {
1246         test_init_done_=t
1247
1248         # skip all tests if there were external prerequisites missing during init
1249         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1250 }
1251
1252
1253 . ./test-lib-common.sh || exit 1
1254
1255 emacs_generate_script
1256
1257
1258 # Use -P to resolve symlinks in our working directory so that the cwd
1259 # in subprocesses like git equals our $PWD (for pathname comparisons).
1260 cd -P "$test" || error "Cannot set up test environment"
1261
1262 if test "$verbose" = "t"
1263 then
1264         exec 4>&2 3>&1
1265 else
1266         exec 4>test.output 3>&4
1267 fi
1268
1269 for skp in $NOTMUCH_SKIP_TESTS
1270 do
1271         to_skip=
1272         for skp in $NOTMUCH_SKIP_TESTS
1273         do
1274                 case "$this_test" in
1275                 $skp)
1276                         to_skip=t
1277                         break
1278                 esac
1279                 case "$this_test_bare" in
1280                 $skp)
1281                         to_skip=t
1282                         break
1283                 esac
1284         done
1285         case "$to_skip" in
1286         t)
1287                 say_color skip >&3 "skipping test $this_test altogether"
1288                 say_color skip "skip all tests in $this_test"
1289                 test_done
1290         esac
1291 done
1292
1293 # Provide an implementation of the 'yes' utility
1294 yes () {
1295         if test $# = 0
1296         then
1297                 y=y
1298         else
1299                 y="$*"
1300         fi
1301
1302         while echo "$y"
1303         do
1304                 :
1305         done
1306 }
1307
1308 # Fix some commands on Windows
1309 case $(uname -s) in
1310 *MINGW*)
1311         # Windows has its own (incompatible) sort and find
1312         sort () {
1313                 /usr/bin/sort "$@"
1314         }
1315         find () {
1316                 /usr/bin/find "$@"
1317         }
1318         sum () {
1319                 md5sum "$@"
1320         }
1321         # git sees Windows-style pwd
1322         pwd () {
1323                 builtin pwd -W
1324         }
1325         # no POSIX permissions
1326         # backslashes in pathspec are converted to '/'
1327         # exec does not inherit the PID
1328         ;;
1329 *)
1330         test_set_prereq POSIXPERM
1331         test_set_prereq BSLASHPSPEC
1332         test_set_prereq EXECKEEPSPID
1333         ;;
1334 esac
1335
1336 test -z "$NO_PERL" && test_set_prereq PERL
1337 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1338
1339 # test whether the filesystem supports symbolic links
1340 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1341 rm -f y
1342
1343 # convert variable from configure to more convenient form
1344 case "$NOTMUCH_DEFAULT_XAPIAN_BACKEND" in
1345     glass)
1346         db_ending=glass
1347     ;;
1348     chert)
1349         db_ending=DB
1350     ;;
1351     *)
1352         error "Unknown Xapian backend $NOTMUCH_DEFAULT_XAPIAN_BACKEND"
1353 esac
1354 # declare prerequisites for external binaries used in tests
1355 test_declare_external_prereq dtach
1356 test_declare_external_prereq emacs
1357 test_declare_external_prereq ${TEST_EMACSCLIENT}
1358 test_declare_external_prereq gdb
1359 test_declare_external_prereq gpg
1360 test_declare_external_prereq openssl
1361 test_declare_external_prereq gpgsm
1362 test_declare_external_prereq ${NOTMUCH_PYTHON}