]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
a1978279e5b46cf0d9a62f257f4efaaa68b2d71f
[notmuch] / test / test-lib.sh
1 #!/bin/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
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         if test -n "$GIT_EXIT_OK"
178         then
179                 exit $code
180         else
181                 echo >&5 "FATAL: Unexpected exit with code $code"
182                 exit 1
183         fi
184 }
185
186 GIT_EXIT_OK=
187 trap 'die' EXIT
188
189 test_decode_color () {
190         sed     -e 's/.\[1m/<WHITE>/g' \
191                 -e 's/.\[31m/<RED>/g' \
192                 -e 's/.\[32m/<GREEN>/g' \
193                 -e 's/.\[33m/<YELLOW>/g' \
194                 -e 's/.\[34m/<BLUE>/g' \
195                 -e 's/.\[35m/<MAGENTA>/g' \
196                 -e 's/.\[36m/<CYAN>/g' \
197                 -e 's/.\[m/<RESET>/g'
198 }
199
200 q_to_nul () {
201         perl -pe 'y/Q/\000/'
202 }
203
204 q_to_cr () {
205         tr Q '\015'
206 }
207
208 append_cr () {
209         sed -e 's/$/Q/' | tr Q '\015'
210 }
211
212 remove_cr () {
213         tr '\015' Q | sed -e 's/Q$//'
214 }
215
216 # Notmuch helper functions
217 increment_mtime_amount=0
218 increment_mtime ()
219 {
220     dir="$1"
221
222     increment_mtime_amount=$((increment_mtime_amount + 1))
223     touch -d "+${increment_mtime_amount} seconds" "$dir"
224 }
225
226 # Generate a new message in the mail directory, with a unique message
227 # ID and subject. The message is not added to the index.
228 #
229 # After this function returns, the filename of the generated message
230 # is available as $gen_msg_filename and the message ID is available as
231 # $gen_msg_id .
232 #
233 # This function supports named parameters with the bash syntax for
234 # assigning a value to an associative array ([name]=value). The
235 # supported parameters are:
236 #
237 #  [dir]=directory/of/choice
238 #
239 #       Generate the message in directory 'directory/of/choice' within
240 #       the mail store. The directory will be created if necessary.
241 #
242 #  [filename]=name
243 #
244 #       Store the message in file 'name'. The default is to store it
245 #       in 'msg-<count>', where <count> is three-digit number of the
246 #       message.
247 #       
248 #  [body]=text
249 #
250 #       Text to use as the body of the email message
251 #
252 #  '[from]="Some User <user@example.com>"'
253 #  '[to]="Some User <user@example.com>"'
254 #  '[subject]="Subject of email message"'
255 #  '[date]="RFC 822 Date"'
256 #
257 #       Values for email headers. If not provided, default values will
258 #       be generated instead.
259 #
260 #  '[cc]="Some User <user@example.com>"'
261 #  [reply-to]=some-address
262 #  [in-reply-to]=<message-id>
263 #  [references]=<message-id>
264 #  [content-type]=content-type-specification
265 #  '[header]=full header line, including keyword'
266 #
267 #       Additional values for email headers. If these are not provided
268 #       then the relevant headers will simply not appear in the
269 #       message.
270 #
271 #  '[id]=message-id'
272 #
273 #       Controls the message-id of the created message.
274 gen_msg_cnt=0
275 gen_msg_filename=""
276 gen_msg_id=""
277 generate_message ()
278 {
279     # This is our (bash-specific) magic for doing named parameters
280     local -A template="($@)"
281     local additional_headers
282
283     gen_msg_cnt=$((gen_msg_cnt + 1))
284     if [ -z "${template[filename]}" ]; then
285         gen_msg_name="msg-$(printf "%03d" $gen_msg_cnt)"
286     else
287         gen_msg_name=${template[filename]}
288     fi
289
290     if [ -z "${template[id]}" ]; then
291         gen_msg_id="${gen_msg_name%:2,*}@notmuch-test-suite"
292     else
293         gen_msg_id="${template[id]}"
294     fi
295
296     if [ -z "${template[dir]}" ]; then
297         gen_msg_filename="${MAIL_DIR}/$gen_msg_name"
298     else
299         gen_msg_filename="${MAIL_DIR}/${template[dir]}/$gen_msg_name"
300         mkdir -p "$(dirname "$gen_msg_filename")"
301     fi
302
303     if [ -z "${template[body]}" ]; then
304         template[body]="This is just a test message (#${gen_msg_cnt})"
305     fi
306
307     if [ -z "${template[from]}" ]; then
308         template[from]="Notmuch Test Suite <test_suite@notmuchmail.org>"
309     fi
310
311     if [ -z "${template[to]}" ]; then
312         template[to]="Notmuch Test Suite <test_suite@notmuchmail.org>"
313     fi
314
315     if [ -z "${template[subject]}" ]; then
316         template[subject]="Test message #${gen_msg_cnt}"
317     fi
318
319     if [ -z "${template[date]}" ]; then
320         template[date]="Tue, 05 Jan 2001 15:43:57 -0000"
321     fi
322
323     additional_headers=""
324     if [ ! -z "${template[header]}" ]; then
325         additional_headers="${template[header]}
326 ${additional_headers}"
327     fi
328
329     if [ ! -z "${template[reply-to]}" ]; then
330         additional_headers="Reply-To: ${template[reply-to]}
331 ${additional_headers}"
332     fi
333
334     if [ ! -z "${template[in-reply-to]}" ]; then
335         additional_headers="In-Reply-To: ${template[in-reply-to]}
336 ${additional_headers}"
337     fi
338
339     if [ ! -z "${template[cc]}" ]; then
340         additional_headers="Cc: ${template[cc]}
341 ${additional_headers}"
342     fi
343
344     if [ ! -z "${template[references]}" ]; then
345         additional_headers="References: ${template[references]}
346 ${additional_headers}"
347     fi
348
349     if [ ! -z "${template[content-type]}" ]; then
350         additional_headers="Content-Type: ${template[content-type]}
351 ${additional_headers}"
352     fi
353
354
355 cat <<EOF >"$gen_msg_filename"
356 From: ${template[from]}
357 To: ${template[to]}
358 Message-Id: <${gen_msg_id}>
359 Subject: ${template[subject]}
360 Date: ${template[date]}
361 ${additional_headers}
362 ${template[body]}
363 EOF
364
365     # Ensure that the mtime of the containing directory is updated
366     increment_mtime "$(dirname "${gen_msg_filename}")"
367 }
368
369 # Generate a new message and add it to the database.
370 #
371 # All of the arguments and return values supported by generate_message
372 # are also supported here, so see that function for details.
373 add_message ()
374 {
375     generate_message "$@" &&
376     notmuch new > /dev/null
377 }
378
379 # Generate a corpus of email and add it to the database.
380 #
381 # This corpus is fixed, (it happens to be 50 messages from early in
382 # the history of the notmuch mailing list), which allows for reliably
383 # testing commands that need to operate on a not-totally-trivial
384 # number of messages.
385 add_email_corpus ()
386 {
387     rm -rf ${MAIL_DIR}
388     if [ -d ../corpus.mail ]; then
389         cp -a ../corpus.mail ${MAIL_DIR}
390     else
391         cp -a ../corpus ${MAIL_DIR}
392         notmuch new >/dev/null
393         cp -a ${MAIL_DIR} ../corpus.mail
394     fi
395 }
396
397 test_begin_subtest ()
398 {
399     if [ -n "$inside_subtest" ]; then
400         exec 1>&6 2>&7          # Restore stdout and stderr
401         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
402     fi
403     test_subtest_name="$1"
404     # Remember stdout and stderr file descriptios and redirect test
405     # output to the previously prepared file descriptors 3 and 4 (see
406     # bellow)
407     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
408     exec 6>&1 7>&2 >&3 2>&4
409     inside_subtest=t
410 }
411
412 # Pass test if two arguments match
413 #
414 # Note: Unlike all other test_expect_* functions, this function does
415 # not accept a test name. Instead, the caller should call
416 # test_begin_subtest before calling this function in order to set the
417 # name.
418 test_expect_equal ()
419 {
420         exec 1>&6 2>&7          # Restore stdout and stderr
421         inside_subtest=
422         test "$#" = 3 && { prereq=$1; shift; } || prereq=
423         test "$#" = 2 ||
424         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
425
426         output="$1"
427         expected="$2"
428         if ! test_skip "$@"
429         then
430                 if [ "$output" = "$expected" ]; then
431                         test_ok_ "$test_subtest_name"
432                 else
433                         testname=$this_test.$test_count
434                         echo "$expected" > $testname.expected
435                         echo "$output" > $testname.output
436                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
437                 fi
438     fi
439 }
440
441 test_expect_equal_failure ()
442 {
443         exec 1>&6 2>&7          # Restore stdout and stderr
444         inside_subtest=
445         test "$#" = 3 && { prereq=$1; shift; } || prereq=
446         test "$#" = 2 ||
447         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
448
449         output="$1"
450         expected="$2"
451         if ! test_skip "$@"
452         then
453                 if [ "$output" = "$expected" ]; then
454                         test_known_broken_ok_ "$test_subtest_name"
455                 else
456                         test_known_broken_failure_ "$test_subtest_name"
457                         testname=$this_test.$test_count
458                         echo "$expected" > $testname.expected
459                         echo "$output" > $testname.output
460                 fi
461     fi
462 }
463
464 NOTMUCH_NEW ()
465 {
466     notmuch new | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
467 }
468
469 notmuch_search_sanitize ()
470 {
471     sed -r -e 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
472 }
473
474 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
475 notmuch_show_sanitize ()
476 {
477     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
478 }
479
480 # End of notmuch helper functions
481
482 # Use test_set_prereq to tell that a particular prerequisite is available.
483 # The prerequisite can later be checked for in two ways:
484 #
485 # - Explicitly using test_have_prereq.
486 #
487 # - Implicitly by specifying the prerequisite tag in the calls to
488 #   test_expect_{success,failure,code}.
489 #
490 # The single parameter is the prerequisite tag (a simple word, in all
491 # capital letters by convention).
492
493 test_set_prereq () {
494         satisfied="$satisfied$1 "
495 }
496 satisfied=" "
497
498 test_have_prereq () {
499         case $satisfied in
500         *" $1 "*)
501                 : yes, have it ;;
502         *)
503                 ! : nope ;;
504         esac
505 }
506
507 # You are not expected to call test_ok_ and test_failure_ directly, use
508 # the text_expect_* functions instead.
509
510 test_ok_ () {
511         test_success=$(($test_success + 1))
512         say_color pass "%-6s" "PASS"
513         echo " $@"
514 }
515
516 test_failure_ () {
517         test_failure=$(($test_failure + 1))
518         say_color error "%-6s" "FAIL"
519         echo " $1"
520         shift
521         echo "$@" | sed -e 's/^/        /'
522         if test "$verbose" != "t"; then cat test.output; fi
523         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
524 }
525
526 test_known_broken_ok_ () {
527         test_fixed=$(($test_fixed+1))
528         say_color pass "%-6s" "FIXED"
529         echo " $@"
530 }
531
532 test_known_broken_failure_ () {
533         test_broken=$(($test_broken+1))
534         say_color pass "%-6s" "BROKEN"
535         echo " $@"
536 }
537
538 test_debug () {
539         test "$debug" = "" || eval "$1"
540 }
541
542 test_run_ () {
543         test_cleanup=:
544         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
545         eval >&3 2>&4 "$1"
546         eval_ret=$?
547         eval >&3 2>&4 "$test_cleanup"
548         return 0
549 }
550
551 test_skip () {
552         test_count=$(($test_count+1))
553         to_skip=
554         for skp in $NOTMUCH_SKIP_TESTS
555         do
556                 case $this_test.$test_count in
557                 $skp)
558                         to_skip=t
559                 esac
560         done
561         if test -z "$to_skip" && test -n "$prereq" &&
562            ! test_have_prereq "$prereq"
563         then
564                 to_skip=t
565         fi
566         case "$to_skip" in
567         t)
568                 say_color skip >&3 "skipping test: $@"
569                 say_color skip "%-6s" "SKIP"
570                 echo " $1"
571                 : true
572                 ;;
573         *)
574                 false
575                 ;;
576         esac
577 }
578
579 test_expect_failure () {
580         test "$#" = 3 && { prereq=$1; shift; } || prereq=
581         test "$#" = 2 ||
582         error "bug in the test script: not 2 or 3 parameters to test-expect-failure"
583         if ! test_skip "$@"
584         then
585                 test_run_ "$2"
586                 if [ "$?" = 0 -a "$eval_ret" = 0 ]
587                 then
588                         test_known_broken_ok_ "$1"
589                 else
590                         test_known_broken_failure_ "$1"
591                 fi
592         fi
593 }
594
595 test_expect_success () {
596         test "$#" = 3 && { prereq=$1; shift; } || prereq=
597         test "$#" = 2 ||
598         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
599         if ! test_skip "$@"
600         then
601                 test_run_ "$2"
602                 if [ "$?" = 0 -a "$eval_ret" = 0 ]
603                 then
604                         test_ok_ "$1"
605                 else
606                         test_failure_ "$@"
607                 fi
608         fi
609 }
610
611 test_expect_code () {
612         test "$#" = 4 && { prereq=$1; shift; } || prereq=
613         test "$#" = 3 ||
614         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
615         if ! test_skip "$@"
616         then
617                 test_run_ "$3"
618                 if [ "$?" = 0 -a "$eval_ret" = "$1" ]
619                 then
620                         test_ok_ "$2"
621                 else
622                         test_failure_ "$@"
623                 fi
624         fi
625 }
626
627 # test_external runs external test scripts that provide continuous
628 # test output about their progress, and succeeds/fails on
629 # zero/non-zero exit code.  It outputs the test output on stdout even
630 # in non-verbose mode, and announces the external script with "* run
631 # <n>: ..." before running it.  When providing relative paths, keep in
632 # mind that all scripts run in "trash directory".
633 # Usage: test_external description command arguments...
634 # Example: test_external 'Perl API' perl ../path/to/test.pl
635 test_external () {
636         test "$#" = 4 && { prereq=$1; shift; } || prereq=
637         test "$#" = 3 ||
638         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
639         descr="$1"
640         shift
641         if ! test_skip "$descr" "$@"
642         then
643                 # Announce the script to reduce confusion about the
644                 # test output that follows.
645                 say_color "" " run $test_count: $descr ($*)"
646                 # Run command; redirect its stderr to &4 as in
647                 # test_run_, but keep its stdout on our stdout even in
648                 # non-verbose mode.
649                 "$@" 2>&4
650                 if [ "$?" = 0 ]
651                 then
652                         test_ok_ "$descr"
653                 else
654                         test_failure_ "$descr" "$@"
655                 fi
656         fi
657 }
658
659 # Like test_external, but in addition tests that the command generated
660 # no output on stderr.
661 test_external_without_stderr () {
662         # The temporary file has no (and must have no) security
663         # implications.
664         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
665         stderr="$tmp/git-external-stderr.$$.tmp"
666         test_external "$@" 4> "$stderr"
667         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
668         descr="no stderr: $1"
669         shift
670         if [ ! -s "$stderr" ]; then
671                 rm "$stderr"
672                 test_ok_ "$descr"
673         else
674                 if [ "$verbose" = t ]; then
675                         output=`echo; echo Stderr is:; cat "$stderr"`
676                 else
677                         output=
678                 fi
679                 # rm first in case test_failure exits.
680                 rm "$stderr"
681                 test_failure_ "$descr" "$@" "$output"
682         fi
683 }
684
685 # This is not among top-level (test_expect_success | test_expect_failure)
686 # but is a prefix that can be used in the test script, like:
687 #
688 #       test_expect_success 'complain and die' '
689 #           do something &&
690 #           do something else &&
691 #           test_must_fail git checkout ../outerspace
692 #       '
693 #
694 # Writing this as "! git checkout ../outerspace" is wrong, because
695 # the failure could be due to a segv.  We want a controlled failure.
696
697 test_must_fail () {
698         "$@"
699         test $? -gt 0 -a $? -le 129 -o $? -gt 192
700 }
701
702 # test_cmp is a helper function to compare actual and expected output.
703 # You can use it like:
704 #
705 #       test_expect_success 'foo works' '
706 #               echo expected >expected &&
707 #               foo >actual &&
708 #               test_cmp expected actual
709 #       '
710 #
711 # This could be written as either "cmp" or "diff -u", but:
712 # - cmp's output is not nearly as easy to read as diff -u
713 # - not all diff versions understand "-u"
714
715 test_cmp() {
716         $GIT_TEST_CMP "$@"
717 }
718
719 # This function can be used to schedule some commands to be run
720 # unconditionally at the end of the test to restore sanity:
721 #
722 #       test_expect_success 'test core.capslock' '
723 #               git config core.capslock true &&
724 #               test_when_finished "git config --unset core.capslock" &&
725 #               hello world
726 #       '
727 #
728 # That would be roughly equivalent to
729 #
730 #       test_expect_success 'test core.capslock' '
731 #               git config core.capslock true &&
732 #               hello world
733 #               git config --unset core.capslock
734 #       '
735 #
736 # except that the greeting and config --unset must both succeed for
737 # the test to pass.
738
739 test_when_finished () {
740         test_cleanup="{ $*
741                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
742 }
743
744 test_done () {
745         GIT_EXIT_OK=t
746         test_results_dir="$TEST_DIRECTORY/test-results"
747         mkdir -p "$test_results_dir"
748         test_results_path="$test_results_dir/${0%.sh}-$$"
749
750         echo "total $test_count" >> $test_results_path
751         echo "success $test_success" >> $test_results_path
752         echo "fixed $test_fixed" >> $test_results_path
753         echo "broken $test_broken" >> $test_results_path
754         echo "failed $test_failure" >> $test_results_path
755         echo "" >> $test_results_path
756
757         echo
758
759         if [ "$test_failure" = "0" ]; then
760             if [ "$test_broken" = "0" ]; then       
761                 rm -rf "$remove_tmp"
762             fi
763             exit 0
764         else
765             exit 1
766         fi
767 }
768
769 test_emacs () {
770         # Construct a little test script here for the benefit of the user,
771         # (who can easily run "run_emacs" to get the same emacs environment
772         # for investigating any failures).    
773         cat <<EOF > run_emacs
774 #!/bin/sh
775 export PATH=$PATH
776 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
777
778 # We assume that the user will give a command-line argument only if
779 # wanting to run in batch mode.
780 if [ \$# -gt 0 ]; then
781         BATCH=--batch
782 fi
783
784 # Here's what we are using here:
785 #
786 # --batch:              Quit after given commands and print all (messages)
787 #
788 # --no-init-file        Don't load users ~/.emacs
789 #
790 # --no-site-file        Don't load the site-wide startup stuff
791 #
792 # --directory           Ensure that the local notmuch.el source is found
793 #
794 # --load                Force loading of notmuch.el
795 #
796 # notmuch-test-wait     Function for tests to use to wait for process completion
797 #
798 # message-signature     Avoiding appending user's signature on messages
799 #
800 # set-frame-width       80 columns (avoids crazy 10-column default of --batch)
801
802 emacs \$BATCH --no-init-file --no-site-file \
803         --directory ../../emacs --load notmuch.el \
804         --eval "(defun notmuch-test-wait ()
805                         (while (get-buffer-process (current-buffer))
806                                 (sleep-for 0.1)))" \
807         --eval "(setq message-signature nil)" \
808         --eval "(progn (set-frame-width (window-frame (get-buffer-window)) 80) \$@)"
809 EOF
810         chmod a+x ./run_emacs
811         ./run_emacs "$@"
812 }
813
814
815 find_notmuch_path ()
816 {
817     dir="$1"
818
819     while [ -n "$dir" ]; do
820         bin="$dir/notmuch"
821         if [ -x "$bin" ]; then
822             echo "$dir"
823             return
824         fi
825         dir="$(dirname "$dir")"
826         if [ "$dir" = "/" ]; then
827             break
828         fi
829     done
830 }
831
832 # Test the binaries we have just built.  The tests are kept in
833 # test/ subdirectory and are run in 'trash directory' subdirectory.
834 TEST_DIRECTORY=$(pwd)
835 if test -n "$valgrind"
836 then
837         make_symlink () {
838                 test -h "$2" &&
839                 test "$1" = "$(readlink "$2")" || {
840                         # be super paranoid
841                         if mkdir "$2".lock
842                         then
843                                 rm -f "$2" &&
844                                 ln -s "$1" "$2" &&
845                                 rm -r "$2".lock
846                         else
847                                 while test -d "$2".lock
848                                 do
849                                         say "Waiting for lock on $2."
850                                         sleep 1
851                                 done
852                         fi
853                 }
854         }
855
856         make_valgrind_symlink () {
857                 # handle only executables
858                 test -x "$1" || return
859
860                 base=$(basename "$1")
861                 symlink_target=$TEST_DIRECTORY/../$base
862                 # do not override scripts
863                 if test -x "$symlink_target" &&
864                     test ! -d "$symlink_target" &&
865                     test "#!" != "$(head -c 2 < "$symlink_target")"
866                 then
867                         symlink_target=../valgrind.sh
868                 fi
869                 case "$base" in
870                 *.sh|*.perl)
871                         symlink_target=../unprocessed-script
872                 esac
873                 # create the link, or replace it if it is out of date
874                 make_symlink "$symlink_target" "$GIT_VALGRIND/bin/$base" || exit
875         }
876
877         # override notmuch executable in TEST_DIRECTORY/..
878         GIT_VALGRIND=$TEST_DIRECTORY/valgrind
879         mkdir -p "$GIT_VALGRIND"/bin
880         make_valgrind_symlink $TEST_DIRECTORY/../notmuch
881         OLDIFS=$IFS
882         IFS=:
883         for path in $PATH
884         do
885                 ls "$path"/notmuch 2> /dev/null |
886                 while read file
887                 do
888                         make_valgrind_symlink "$file"
889                 done
890         done
891         IFS=$OLDIFS
892         PATH=$GIT_VALGRIND/bin:$PATH
893         GIT_EXEC_PATH=$GIT_VALGRIND/bin
894         export GIT_VALGRIND
895 else # normal case
896         notmuch_path=`find_notmuch_path "$TEST_DIRECTORY"`
897         test -n "$notmuch_path" && PATH="$notmuch_path:$PATH"
898 fi
899 export PATH
900
901 # Test repository
902 test="tmp.$(basename "$0" .sh)"
903 test -n "$root" && test="$root/$test"
904 case "$test" in
905 /*) TMP_DIRECTORY="$test" ;;
906  *) TMP_DIRECTORY="$TEST_DIRECTORY/$test" ;;
907 esac
908 test ! -z "$debug" || remove_tmp=$TMP_DIRECTORY
909 rm -fr "$test" || {
910         GIT_EXIT_OK=t
911         echo >&5 "FATAL: Cannot prepare test area"
912         exit 1
913 }
914
915 MAIL_DIR="${TMP_DIRECTORY}/mail"
916 export NOTMUCH_CONFIG="${TMP_DIRECTORY}/notmuch-config"
917
918 mkdir -p "${test}"
919 mkdir -p "${MAIL_DIR}"
920
921 cat <<EOF >"${NOTMUCH_CONFIG}"
922 [database]
923 path=${MAIL_DIR}
924
925 [user]
926 name=Notmuch Test Suite
927 primary_email=test_suite@notmuchmail.org
928 other_email=test_suite_other@notmuchmail.org;test_suite@otherdomain.org
929 EOF
930
931
932 # Use -P to resolve symlinks in our working directory so that the cwd
933 # in subprocesses like git equals our $PWD (for pathname comparisons).
934 cd -P "$test" || error "Cannot setup test environment"
935
936 if test "$verbose" = "t"
937 then
938         exec 4>&2 3>&1
939 else
940         exec 4>test.output 3>&4
941 fi
942
943 this_test=${0##*/}
944 for skp in $NOTMUCH_SKIP_TESTS
945 do
946         to_skip=
947         for skp in $NOTMUCH_SKIP_TESTS
948         do
949                 case "$this_test" in
950                 $skp)
951                         to_skip=t
952                 esac
953         done
954         case "$to_skip" in
955         t)
956                 say_color skip >&3 "skipping test $this_test altogether"
957                 say_color skip "skip all tests in $this_test"
958                 test_done
959         esac
960 done
961
962 # Provide an implementation of the 'yes' utility
963 yes () {
964         if test $# = 0
965         then
966                 y=y
967         else
968                 y="$*"
969         fi
970
971         while echo "$y"
972         do
973                 :
974         done
975 }
976
977 # Fix some commands on Windows
978 case $(uname -s) in
979 *MINGW*)
980         # Windows has its own (incompatible) sort and find
981         sort () {
982                 /usr/bin/sort "$@"
983         }
984         find () {
985                 /usr/bin/find "$@"
986         }
987         sum () {
988                 md5sum "$@"
989         }
990         # git sees Windows-style pwd
991         pwd () {
992                 builtin pwd -W
993         }
994         # no POSIX permissions
995         # backslashes in pathspec are converted to '/'
996         # exec does not inherit the PID
997         ;;
998 *)
999         test_set_prereq POSIXPERM
1000         test_set_prereq BSLASHPSPEC
1001         test_set_prereq EXECKEEPSPID
1002         ;;
1003 esac
1004
1005 test -z "$NO_PERL" && test_set_prereq PERL
1006 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1007
1008 # test whether the filesystem supports symbolic links
1009 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1010 rm -f y