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