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