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