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