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