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