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