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