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