]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: move generate_message, add_message into test-lib-common.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 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     output=$(echo "$1" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -mjson.tool \
454         || echo "$1")
455     expected=$(echo "$2" | PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -mjson.tool \
456         || echo "$2")
457     shift 2
458     test_expect_equal "$output" "$expected" "$@"
459 }
460
461 # Sort the top-level list of JSON data from stdin.
462 test_sort_json () {
463     PYTHONIOENCODING=utf-8 $NOTMUCH_PYTHON -c \
464         "import sys, json; json.dump(sorted(json.load(sys.stdin)),sys.stdout)"
465 }
466
467 test_emacs_expect_t () {
468         test "$#" = 1 ||
469         error "bug in the test script: not 1 parameter to test_emacs_expect_t"
470         if [ -z "$inside_subtest" ]; then
471                 error "bug in the test script: test_emacs_expect_t without test_begin_subtest"
472         fi
473
474         # Run the test.
475         if ! test_skip "$test_subtest_name"
476         then
477                 test_emacs "(notmuch-test-run $1)" >/dev/null
478
479                 # Restore state after the test.
480                 exec 1>&6 2>&7          # Restore stdout and stderr
481                 inside_subtest=
482
483                 # Report success/failure.
484                 result=$(cat OUTPUT)
485                 if [ "$result" = t ]
486                 then
487                         test_ok_
488                 else
489                         test_failure_ "${result}"
490                 fi
491         else
492                 # Restore state after the (non) test.
493                 exec 1>&6 2>&7          # Restore stdout and stderr
494                 inside_subtest=
495         fi
496 }
497
498 NOTMUCH_NEW ()
499 {
500     notmuch new "${@}" | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
501 }
502
503 NOTMUCH_DUMP_TAGS ()
504 {
505     # this relies on the default format being batch-tag, otherwise some tests will break
506     notmuch dump --include=tags "${@}" | sed '/^#/d' | sort
507 }
508
509 notmuch_search_sanitize ()
510 {
511     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
512 }
513
514 notmuch_search_files_sanitize ()
515 {
516     notmuch_dir_sanitize
517 }
518
519 notmuch_dir_sanitize ()
520 {
521     sed -e "s,$MAIL_DIR,MAIL_DIR," -e "s,${PWD},CWD,g" "$@"
522 }
523
524 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
525 notmuch_show_sanitize ()
526 {
527     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
528 }
529 notmuch_show_sanitize_all ()
530 {
531     sed \
532         -e 's| filename:.*| filename:XXXXX|' \
533         -e 's| id:[^ ]* | id:XXXXX |' | \
534         notmuch_date_sanitize
535 }
536
537 notmuch_json_show_sanitize ()
538 {
539     sed \
540         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
541         -e 's|"Date": "Fri, 05 Jan 2001 [^"]*0000"|"Date": "GENERATED_DATE"|g' \
542         -e 's|"filename": "signature.asc",||g' \
543         -e 's|"filename": \["/[^"]*"\],|"filename": \["YYYYY"\],|g' \
544         -e 's|"timestamp": 97.......|"timestamp": 42|g' \
545         -e 's|"content-length": [1-9][0-9]*|"content-length": "NONZERO"|g'
546 }
547
548 notmuch_emacs_error_sanitize ()
549 {
550     local command=$1
551     shift
552     for file in "$@"; do
553         echo "=== $file ==="
554         cat "$file"
555     done | sed  \
556         -e 's/^\[.*\]$/[XXX]/' \
557         -e "s|^\(command: \)\{0,1\}/.*/$command|\1YYY/$command|"
558 }
559
560 notmuch_date_sanitize ()
561 {
562     sed \
563         -e 's/^Date: Fri, 05 Jan 2001 .*0000/Date: GENERATED_DATE/'
564 }
565
566 notmuch_uuid_sanitize ()
567 {
568     sed 's/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}/UUID/g'
569 }
570
571 notmuch_built_with_sanitize ()
572 {
573     sed 's/^built_with[.]\(.*\)=.*$/built_with.\1=something/'
574 }
575
576 notmuch_config_sanitize ()
577 {
578     notmuch_dir_sanitize | notmuch_built_with_sanitize
579 }
580
581 # End of notmuch helper functions
582
583 # Use test_set_prereq to tell that a particular prerequisite is available.
584 #
585 # The prerequisite can later be checked for by using test_have_prereq.
586 #
587 # The single parameter is the prerequisite tag (a simple word, in all
588 # capital letters by convention).
589
590 test_set_prereq () {
591         satisfied="$satisfied$1 "
592 }
593 satisfied=" "
594
595 test_have_prereq () {
596         case $satisfied in
597         *" $1 "*)
598                 : yes, have it ;;
599         *)
600                 ! : nope ;;
601         esac
602 }
603
604 declare -A test_missing_external_prereq_
605 declare -A test_subtest_missing_external_prereq_
606
607 # declare prerequisite for the given external binary
608 test_declare_external_prereq () {
609         binary="$1"
610         test "$#" = 2 && name=$2 || name="$binary(1)"
611
612         if ! hash $binary 2>/dev/null; then
613                 test_missing_external_prereq_["${binary}"]=t
614                 eval "
615 $binary () {
616         test_subtest_missing_external_prereq_[\"${name}\"]=t
617         false
618 }"
619         fi
620 }
621
622 # Explicitly require external prerequisite.  Useful when binary is
623 # called indirectly (e.g. from emacs).
624 # Returns success if dependency is available, failure otherwise.
625 test_require_external_prereq () {
626         binary="$1"
627         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
628                 # dependency is missing, call the replacement function to note it
629                 eval "$binary"
630         else
631                 true
632         fi
633 }
634
635 # You are not expected to call test_ok_ and test_failure_ directly, use
636 # the text_expect_* functions instead.
637
638 test_ok_ () {
639         if test "$test_subtest_known_broken_" = "t"; then
640                 test_known_broken_ok_
641                 return
642         fi
643         test_success=$(($test_success + 1))
644         if test -n "$NOTMUCH_TEST_QUIET"; then
645                 return 0
646         fi
647         say_color pass "%-6s" "PASS"
648         echo " $test_subtest_name"
649 }
650
651 test_failure_ () {
652         print_test_description
653         if test "$test_subtest_known_broken_" = "t"; then
654                 test_known_broken_failure_ "$@"
655                 return
656         fi
657         test_failure=$(($test_failure + 1))
658         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
659         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
660         return 1
661 }
662
663 test_failure_message_ () {
664         say_color error "%-6s" "$1"
665         echo " $2"
666         shift 2
667         if [ "$#" != "0" ]; then
668                 echo "$@" | sed -e 's/^/        /'
669         fi
670         if test "$verbose" != "t"; then cat test.output; fi
671 }
672
673 test_known_broken_ok_ () {
674         test_reset_state_
675         test_fixed=$(($test_fixed+1))
676         say_color pass "%-6s" "FIXED"
677         echo " $test_subtest_name"
678 }
679
680 test_known_broken_failure_ () {
681         test_reset_state_
682         test_broken=$(($test_broken+1))
683         if [ -z "$NOTMUCH_TEST_QUIET" ]; then
684                 test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
685         else
686                 test_failure_message_ "BROKEN" "$test_subtest_name"
687         fi
688         return 1
689 }
690
691 test_debug () {
692         test "$debug" = "" || eval "$1"
693 }
694
695 test_run_ () {
696         test_cleanup=:
697         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
698         eval >&3 2>&4 "$1"
699         eval_ret=$?
700         eval >&3 2>&4 "$test_cleanup"
701         return 0
702 }
703
704 test_skip () {
705         test_count=$(($test_count+1))
706         to_skip=
707         for skp in $NOTMUCH_SKIP_TESTS
708         do
709                 case $this_test.$test_count in
710                 $skp)
711                         to_skip=t
712                         break
713                 esac
714                 case $this_test_bare.$test_count in
715                 $skp)
716                         to_skip=t
717                         break
718                 esac
719         done
720         case "$to_skip" in
721         t)
722                 test_report_skip_ "$@"
723                 ;;
724         *)
725                 test_check_missing_external_prereqs_ "$@"
726                 ;;
727         esac
728 }
729
730 test_check_missing_external_prereqs_ () {
731         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
732                 say_color skip >&1 "missing prerequisites: "
733                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
734                 test_report_skip_ "$@"
735         else
736                 false
737         fi
738 }
739
740 test_report_skip_ () {
741         test_reset_state_
742         say_color skip >&3 "skipping test:"
743         echo " $@" >&3
744         say_color skip "%-6s" "SKIP"
745         echo " $1"
746 }
747
748 test_subtest_known_broken () {
749         test_subtest_known_broken_=t
750 }
751
752 test_expect_success () {
753         exec 1>&6 2>&7          # Restore stdout and stderr
754         if [ -z "$inside_subtest" ]; then
755                 error "bug in the test script: test_expect_success without test_begin_subtest"
756         fi
757         inside_subtest=
758         test "$#" = 1 ||
759         error "bug in the test script: not 1 parameters to test_expect_success"
760
761         if ! test_skip "$test_subtest_name"
762         then
763                 test_run_ "$1"
764                 run_ret="$?"
765                 # test_run_ may update missing external prerequisites
766                 test_check_missing_external_prereqs_ "$@" ||
767                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
768                 then
769                         test_ok_
770                 else
771                         test_failure_ "$1"
772                 fi
773         fi
774 }
775
776 test_expect_code () {
777         exec 1>&6 2>&7          # Restore stdout and stderr
778         if [ -z "$inside_subtest" ]; then
779                 error "bug in the test script: test_expect_code without test_begin_subtest"
780         fi
781         inside_subtest=
782         test "$#" = 2 ||
783         error "bug in the test script: not 2 parameters to test_expect_code"
784
785         if ! test_skip "$test_subtest_name"
786         then
787                 test_run_ "$2"
788                 run_ret="$?"
789                 # test_run_ may update missing external prerequisites,
790                 test_check_missing_external_prereqs_ "$@" ||
791                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
792                 then
793                         test_ok_
794                 else
795                         test_failure_ "exit code $eval_ret, expected $1" "$2"
796                 fi
797         fi
798 }
799
800 # This is not among top-level (test_expect_success)
801 # but is a prefix that can be used in the test script, like:
802 #
803 #       test_expect_success 'complain and die' '
804 #           do something &&
805 #           do something else &&
806 #           test_must_fail git checkout ../outerspace
807 #       '
808 #
809 # Writing this as "! git checkout ../outerspace" is wrong, because
810 # the failure could be due to a segv.  We want a controlled failure.
811
812 test_must_fail () {
813         "$@"
814         test $? -gt 0 -a $? -le 129 -o $? -gt 192
815 }
816
817 # test_cmp is a helper function to compare actual and expected output.
818 # You can use it like:
819 #
820 #       test_expect_success 'foo works' '
821 #               echo expected >expected &&
822 #               foo >actual &&
823 #               test_cmp expected actual
824 #       '
825 #
826 # This could be written as either "cmp" or "diff -u", but:
827 # - cmp's output is not nearly as easy to read as diff -u
828 # - not all diff versions understand "-u"
829
830 test_cmp() {
831         $GIT_TEST_CMP "$@"
832 }
833
834 # This function can be used to schedule some commands to be run
835 # unconditionally at the end of the test to restore sanity:
836 #
837 #       test_expect_success 'test core.capslock' '
838 #               git config core.capslock true &&
839 #               test_when_finished "git config --unset core.capslock" &&
840 #               hello world
841 #       '
842 #
843 # That would be roughly equivalent to
844 #
845 #       test_expect_success 'test core.capslock' '
846 #               git config core.capslock true &&
847 #               hello world
848 #               git config --unset core.capslock
849 #       '
850 #
851 # except that the greeting and config --unset must both succeed for
852 # the test to pass.
853
854 test_when_finished () {
855         test_cleanup="{ $*
856                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
857 }
858
859 test_done () {
860         GIT_EXIT_OK=t
861         test_results_dir="$TEST_DIRECTORY/test-results"
862         mkdir -p "$test_results_dir"
863         test_results_path="$test_results_dir/$this_test"
864
865         echo "total $test_count" >> $test_results_path
866         echo "success $test_success" >> $test_results_path
867         echo "fixed $test_fixed" >> $test_results_path
868         echo "broken $test_broken" >> $test_results_path
869         echo "failed $test_failure" >> $test_results_path
870         echo "" >> $test_results_path
871
872         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
873
874         if [ "$test_failure" = "0" ]; then
875             if [ "$test_broken" = "0" ]; then
876                 rm -rf "$remove_tmp"
877             fi
878             exit 0
879         else
880             exit 1
881         fi
882 }
883
884 emacs_generate_script () {
885         # Construct a little test script here for the benefit of the user,
886         # (who can easily run "run_emacs" to get the same emacs environment
887         # for investigating any failures).
888         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
889 #!/bin/sh
890 export PATH=$PATH
891 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
892
893 # Here's what we are using here:
894 #
895 # --quick              Use minimal customization. This implies --no-init-file,
896 #                      --no-site-file and (emacs 24) --no-site-lisp
897 #
898 # --directory           Ensure that the local elisp sources are found
899 #
900 # --load                Force loading of notmuch.el and test-lib.el
901
902 exec ${TEST_EMACS} --quick \
903         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
904         --directory "$TEST_DIRECTORY" --load test-lib.el \
905         "\$@"
906 EOF
907         chmod a+x "$TMP_DIRECTORY/run_emacs"
908 }
909
910 test_emacs () {
911         # test dependencies beforehand to avoid the waiting loop below
912         missing_dependencies=
913         test_require_external_prereq dtach || missing_dependencies=1
914         test_require_external_prereq emacs || missing_dependencies=1
915         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
916         test -z "$missing_dependencies" || return
917
918         if [ -z "$EMACS_SERVER" ]; then
919                 emacs_tests="${this_test_bare}.el"
920                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
921                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
922                 else
923                         load_emacs_tests=
924                 fi
925                 server_name="notmuch-test-suite-$$"
926                 # start a detached session with an emacs server
927                 # user's TERM (or 'vt100' in case user's TERM is known dumb
928                 # or unknown) is given to dtach which assumes a minimally
929                 # VT100-compatible terminal -- and emacs inherits that
930                 TERM=$SMART_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
931                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
932                                 --no-window-system \
933                                 $load_emacs_tests \
934                                 --eval '(setq server-name \"$server_name\")' \
935                                 --eval '(server-start)' \
936                                 --eval '(orphan-watchdog $$)'" || return
937                 EMACS_SERVER="$server_name"
938                 # wait until the emacs server is up
939                 until test_emacs '()' >/dev/null 2>/dev/null; do
940                         sleep 1
941                 done
942         fi
943
944         # Clear test-output output file.  Most Emacs tests end with a
945         # call to (test-output).  If the test code fails with an
946         # exception before this call, the output file won't get
947         # updated.  Since we don't want to compare against an output
948         # file from another test, so start out with an empty file.
949         rm -f OUTPUT
950         touch OUTPUT
951
952         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(notmuch-test-progn $@)"
953 }
954
955 test_python() {
956     # Note: if there is need to print debug information from python program,
957     # use stdout = os.fdopen(6, 'w') or stderr = os.fdopen(7, 'w')
958     PYTHONPATH="$NOTMUCH_SRCDIR/bindings/python${PYTHONPATH:+:$PYTHONPATH}" \
959         $NOTMUCH_PYTHON -B - > OUTPUT
960 }
961
962 test_ruby() {
963     MAIL_DIR=$MAIL_DIR ruby -I $TEST_DIRECTORY/../bindings/ruby> OUTPUT
964 }
965
966 test_C () {
967     exec_file="test${test_count}"
968     test_file="${exec_file}.c"
969     cat > ${test_file}
970     ${TEST_CC} ${TEST_CFLAGS} -I${TEST_DIRECTORY} -I${NOTMUCH_SRCDIR}/lib -o ${exec_file} ${test_file} -L${TEST_DIRECTORY}/../lib/ -lnotmuch -ltalloc
971     echo "== stdout ==" > OUTPUT.stdout
972     echo "== stderr ==" > OUTPUT.stderr
973     ./${exec_file} "$@" 1>>OUTPUT.stdout 2>>OUTPUT.stderr
974     notmuch_dir_sanitize OUTPUT.stdout OUTPUT.stderr > OUTPUT
975 }
976
977
978 # Creates a script that counts how much time it is executed and calls
979 # notmuch.  $notmuch_counter_command is set to the path to the
980 # generated script.  Use notmuch_counter_value() function to get the
981 # current counter value.
982 notmuch_counter_reset () {
983         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
984         if [ ! -x "$notmuch_counter_command" ]; then
985                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
986                 cat >"$notmuch_counter_command" <<EOF || return
987 #!/bin/sh
988
989 read count < "$notmuch_counter_state_path"
990 echo \$((count + 1)) > "$notmuch_counter_state_path"
991
992 exec notmuch "\$@"
993 EOF
994                 chmod +x "$notmuch_counter_command" || return
995         fi
996
997         echo 0 > "$notmuch_counter_state_path"
998 }
999
1000 # Returns the current notmuch counter value.
1001 notmuch_counter_value () {
1002         if [ -r "$notmuch_counter_state_path" ]; then
1003                 read count < "$notmuch_counter_state_path"
1004         else
1005                 count=0
1006         fi
1007         echo $count
1008 }
1009
1010 test_reset_state_ () {
1011         test -z "$test_init_done_" && test_init_
1012
1013         test_subtest_known_broken_=
1014         test_subtest_missing_external_prereq_=()
1015 }
1016
1017 # called once before the first subtest
1018 test_init_ () {
1019         test_init_done_=t
1020
1021         # skip all tests if there were external prerequisites missing during init
1022         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1023 }
1024
1025
1026 . ./test-lib-common.sh || exit 1
1027
1028 if [ "${NOTMUCH_GMIME_MAJOR}" = 3 ]; then
1029     test_subtest_broken_gmime_3 () {
1030         test_subtest_known_broken
1031     }
1032     test_subtest_broken_gmime_2 () {
1033         true
1034     }
1035 else
1036     test_subtest_broken_gmime_3 () {
1037         true
1038     }
1039     test_subtest_broken_gmime_2 () {
1040         test_subtest_known_broken
1041     }
1042 fi
1043
1044 emacs_generate_script
1045
1046
1047 # Use -P to resolve symlinks in our working directory so that the cwd
1048 # in subprocesses like git equals our $PWD (for pathname comparisons).
1049 cd -P "$test" || error "Cannot set up test environment"
1050
1051 if test "$verbose" = "t"
1052 then
1053         exec 4>&2 3>&1
1054 else
1055         exec 4>test.output 3>&4
1056 fi
1057
1058 for skp in $NOTMUCH_SKIP_TESTS
1059 do
1060         to_skip=
1061         for skp in $NOTMUCH_SKIP_TESTS
1062         do
1063                 case "$this_test" in
1064                 $skp)
1065                         to_skip=t
1066                         break
1067                 esac
1068                 case "$this_test_bare" in
1069                 $skp)
1070                         to_skip=t
1071                         break
1072                 esac
1073         done
1074         case "$to_skip" in
1075         t)
1076                 say_color skip >&3 "skipping test $this_test altogether"
1077                 say_color skip "skip all tests in $this_test"
1078                 test_done
1079         esac
1080 done
1081
1082 # Provide an implementation of the 'yes' utility
1083 yes () {
1084         if test $# = 0
1085         then
1086                 y=y
1087         else
1088                 y="$*"
1089         fi
1090
1091         while echo "$y"
1092         do
1093                 :
1094         done
1095 }
1096
1097 # Fix some commands on Windows
1098 case $(uname -s) in
1099 *MINGW*)
1100         # Windows has its own (incompatible) sort and find
1101         sort () {
1102                 /usr/bin/sort "$@"
1103         }
1104         find () {
1105                 /usr/bin/find "$@"
1106         }
1107         sum () {
1108                 md5sum "$@"
1109         }
1110         # git sees Windows-style pwd
1111         pwd () {
1112                 builtin pwd -W
1113         }
1114         # no POSIX permissions
1115         # backslashes in pathspec are converted to '/'
1116         # exec does not inherit the PID
1117         ;;
1118 *)
1119         test_set_prereq POSIXPERM
1120         test_set_prereq BSLASHPSPEC
1121         test_set_prereq EXECKEEPSPID
1122         ;;
1123 esac
1124
1125 test -z "$NO_PERL" && test_set_prereq PERL
1126 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1127
1128 # test whether the filesystem supports symbolic links
1129 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1130 rm -f y
1131
1132 # convert variable from configure to more convenient form
1133 case "$NOTMUCH_DEFAULT_XAPIAN_BACKEND" in
1134     glass)
1135         db_ending=glass
1136     ;;
1137     chert)
1138         db_ending=DB
1139     ;;
1140     *)
1141         error "Unknown Xapian backend $NOTMUCH_DEFAULT_XAPIAN_BACKEND"
1142 esac
1143 # declare prerequisites for external binaries used in tests
1144 test_declare_external_prereq dtach
1145 test_declare_external_prereq emacs
1146 test_declare_external_prereq ${TEST_EMACSCLIENT}
1147 test_declare_external_prereq ${TEST_GDB}
1148 test_declare_external_prereq gpg
1149 test_declare_external_prereq openssl
1150 test_declare_external_prereq gpgsm
1151 test_declare_external_prereq ${NOTMUCH_PYTHON}