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