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