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