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