]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: use subtest name for generated message subject by default
[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         output="$1"
501         expected="$2"
502         if ! test_skip "$test_subtest_name"
503         then
504                 if diff -q "$expected" "$output" >/dev/null ; then
505                         test_ok_ "$test_subtest_name"
506                 else
507                         testname=$this_test.$test_count
508                         cp "$output" $testname.output
509                         cp "$expected" $testname.expected
510                         test_failure_ "$test_subtest_name" "$(diff -u $testname.expected $testname.output)"
511                 fi
512     fi
513 }
514
515 test_emacs_expect_t () {
516         test "$#" = 2 && { prereq=$1; shift; } || prereq=
517         test "$#" = 1 ||
518         error "bug in the test script: not 1 or 2 parameters to test_emacs_expect_t"
519
520         # Run the test.
521         if ! test_skip "$test_subtest_name"
522         then
523                 test_emacs "(notmuch-test-run $1)" >/dev/null
524
525                 # Restore state after the test.
526                 exec 1>&6 2>&7          # Restore stdout and stderr
527                 inside_subtest=
528
529                 # Report success/failure.
530                 result=$(cat OUTPUT)
531                 if [ "$result" = t ]
532                 then
533                         test_ok_ "$test_subtest_name"
534                 else
535                         test_failure_ "$test_subtest_name" "${result}"
536                 fi
537         else
538                 # Restore state after the (non) test.
539                 exec 1>&6 2>&7          # Restore stdout and stderr
540                 inside_subtest=
541         fi
542 }
543
544 NOTMUCH_NEW ()
545 {
546     notmuch new | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
547 }
548
549 notmuch_search_sanitize ()
550 {
551     sed -r -e 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
552 }
553
554 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
555 notmuch_show_sanitize ()
556 {
557     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
558 }
559 notmuch_show_sanitize_all ()
560 {
561     sed \
562         -e 's| filename:.*| filename:XXXXX|' \
563         -e 's| id:[^ ]* | id:XXXXX |'
564 }
565
566 notmuch_json_show_sanitize ()
567 {
568     sed -e 's|, |,\n |g' | \
569         sed \
570         -e 's|"id": "[^"]*",|"id": "XXXXX",|' \
571         -e 's|"filename": "[^"]*",|"filename": "YYYYY",|'
572 }
573
574 # End of notmuch helper functions
575
576 # Use test_set_prereq to tell that a particular prerequisite is available.
577 # The prerequisite can later be checked for in two ways:
578 #
579 # - Explicitly using test_have_prereq.
580 #
581 # - Implicitly by specifying the prerequisite tag in the calls to
582 #   test_expect_{success,failure,code}.
583 #
584 # The single parameter is the prerequisite tag (a simple word, in all
585 # capital letters by convention).
586
587 test_set_prereq () {
588         satisfied="$satisfied$1 "
589 }
590 satisfied=" "
591
592 test_have_prereq () {
593         case $satisfied in
594         *" $1 "*)
595                 : yes, have it ;;
596         *)
597                 ! : nope ;;
598         esac
599 }
600
601 # declare prerequisite for the given external binary
602 test_declare_external_prereq () {
603         binary="$1"
604         test "$#" = 2 && name=$2 || name="$binary(1)"
605
606         hash $binary 2>/dev/null || eval "
607         test_missing_external_prereq_${binary}_=t
608 $binary () {
609         echo -n \"\$test_subtest_missing_external_prereqs_ \" | grep -qe \" $name \" ||
610         test_subtest_missing_external_prereqs_=\"\$test_subtest_missing_external_prereqs_ $name\"
611         false
612 }"
613 }
614
615 # Explicitly require external prerequisite.  Useful when binary is
616 # called indirectly (e.g. from emacs).
617 # Returns success if dependency is available, failure otherwise.
618 test_require_external_prereq () {
619         binary="$1"
620         if [ "$(eval echo -n \$test_missing_external_prereq_${binary}_)" = t ]; then
621                 # dependency is missing, call the replacement function to note it
622                 eval "$binary"
623         else
624                 true
625         fi
626 }
627
628 # You are not expected to call test_ok_ and test_failure_ directly, use
629 # the text_expect_* functions instead.
630
631 test_ok_ () {
632         if test "$test_subtest_known_broken_" = "t"; then
633                 test_known_broken_ok_ "$@"
634                 return
635         fi
636         test_success=$(($test_success + 1))
637         say_color pass "%-6s" "PASS"
638         echo " $@"
639 }
640
641 test_failure_ () {
642         if test "$test_subtest_known_broken_" = "t"; then
643                 test_known_broken_failure_ "$@"
644                 return
645         fi
646         test_failure=$(($test_failure + 1))
647         test_failure_message_ "FAIL" "$@"
648         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
649         return 1
650 }
651
652 test_failure_message_ () {
653         say_color error "%-6s" "$1"
654         echo " $2"
655         shift 2
656         echo "$@" | sed -e 's/^/        /'
657         if test "$verbose" != "t"; then cat test.output; fi
658 }
659
660 test_known_broken_ok_ () {
661         test_reset_state_
662         test_fixed=$(($test_fixed+1))
663         say_color pass "%-6s" "FIXED"
664         echo " $@"
665 }
666
667 test_known_broken_failure_ () {
668         test_reset_state_
669         test_broken=$(($test_broken+1))
670         test_failure_message_ "BROKEN" "$@"
671         return 1
672 }
673
674 test_debug () {
675         test "$debug" = "" || eval "$1"
676 }
677
678 test_run_ () {
679         test_cleanup=:
680         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
681         eval >&3 2>&4 "$1"
682         eval_ret=$?
683         eval >&3 2>&4 "$test_cleanup"
684         return 0
685 }
686
687 test_skip () {
688         test_count=$(($test_count+1))
689         to_skip=
690         for skp in $NOTMUCH_SKIP_TESTS
691         do
692                 case $this_test.$test_count in
693                 $skp)
694                         to_skip=t
695                 esac
696         done
697         if test -z "$to_skip" && test -n "$prereq" &&
698            ! test_have_prereq "$prereq"
699         then
700                 to_skip=t
701         fi
702         case "$to_skip" in
703         t)
704                 test_report_skip_ "$@"
705                 ;;
706         *)
707                 test_check_missing_external_prereqs_ "$@"
708                 ;;
709         esac
710 }
711
712 test_check_missing_external_prereqs_ () {
713         if test -n "$test_subtest_missing_external_prereqs_"; then
714                 say_color skip >&1 "missing prerequisites:"
715                 echo "$test_subtest_missing_external_prereqs_" >&1
716                 test_report_skip_ "$@"
717         else
718                 false
719         fi
720 }
721
722 test_report_skip_ () {
723         test_reset_state_
724         say_color skip >&3 "skipping test:"
725         echo " $@" >&3
726         say_color skip "%-6s" "SKIP"
727         echo " $1"
728 }
729
730 test_subtest_known_broken () {
731         test_subtest_known_broken_=t
732 }
733
734 test_expect_success () {
735         test "$#" = 3 && { prereq=$1; shift; } || prereq=
736         test "$#" = 2 ||
737         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
738         test_reset_state_
739         if ! test_skip "$@"
740         then
741                 test_run_ "$2"
742                 run_ret="$?"
743                 # test_run_ may update missing external prerequisites
744                 test_check_missing_external_prereqs_ "$@" ||
745                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
746                 then
747                         test_ok_ "$1"
748                 else
749                         test_failure_ "$@"
750                 fi
751         fi
752 }
753
754 test_expect_code () {
755         test "$#" = 4 && { prereq=$1; shift; } || prereq=
756         test "$#" = 3 ||
757         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
758         test_reset_state_
759         if ! test_skip "$@"
760         then
761                 test_run_ "$3"
762                 run_ret="$?"
763                 # test_run_ may update missing external prerequisites,
764                 test_check_missing_external_prereqs_ "$@" ||
765                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
766                 then
767                         test_ok_ "$2"
768                 else
769                         test_failure_ "$@"
770                 fi
771         fi
772 }
773
774 # test_external runs external test scripts that provide continuous
775 # test output about their progress, and succeeds/fails on
776 # zero/non-zero exit code.  It outputs the test output on stdout even
777 # in non-verbose mode, and announces the external script with "* run
778 # <n>: ..." before running it.  When providing relative paths, keep in
779 # mind that all scripts run in "trash directory".
780 # Usage: test_external description command arguments...
781 # Example: test_external 'Perl API' perl ../path/to/test.pl
782 test_external () {
783         test "$#" = 4 && { prereq=$1; shift; } || prereq=
784         test "$#" = 3 ||
785         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
786         descr="$1"
787         shift
788         test_reset_state_
789         if ! test_skip "$descr" "$@"
790         then
791                 # Announce the script to reduce confusion about the
792                 # test output that follows.
793                 say_color "" " run $test_count: $descr ($*)"
794                 # Run command; redirect its stderr to &4 as in
795                 # test_run_, but keep its stdout on our stdout even in
796                 # non-verbose mode.
797                 "$@" 2>&4
798                 if [ "$?" = 0 ]
799                 then
800                         test_ok_ "$descr"
801                 else
802                         test_failure_ "$descr" "$@"
803                 fi
804         fi
805 }
806
807 # Like test_external, but in addition tests that the command generated
808 # no output on stderr.
809 test_external_without_stderr () {
810         # The temporary file has no (and must have no) security
811         # implications.
812         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
813         stderr="$tmp/git-external-stderr.$$.tmp"
814         test_external "$@" 4> "$stderr"
815         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
816         descr="no stderr: $1"
817         shift
818         if [ ! -s "$stderr" ]; then
819                 rm "$stderr"
820                 test_ok_ "$descr"
821         else
822                 if [ "$verbose" = t ]; then
823                         output=`echo; echo Stderr is:; cat "$stderr"`
824                 else
825                         output=
826                 fi
827                 # rm first in case test_failure exits.
828                 rm "$stderr"
829                 test_failure_ "$descr" "$@" "$output"
830         fi
831 }
832
833 # This is not among top-level (test_expect_success)
834 # but is a prefix that can be used in the test script, like:
835 #
836 #       test_expect_success 'complain and die' '
837 #           do something &&
838 #           do something else &&
839 #           test_must_fail git checkout ../outerspace
840 #       '
841 #
842 # Writing this as "! git checkout ../outerspace" is wrong, because
843 # the failure could be due to a segv.  We want a controlled failure.
844
845 test_must_fail () {
846         "$@"
847         test $? -gt 0 -a $? -le 129 -o $? -gt 192
848 }
849
850 # test_cmp is a helper function to compare actual and expected output.
851 # You can use it like:
852 #
853 #       test_expect_success 'foo works' '
854 #               echo expected >expected &&
855 #               foo >actual &&
856 #               test_cmp expected actual
857 #       '
858 #
859 # This could be written as either "cmp" or "diff -u", but:
860 # - cmp's output is not nearly as easy to read as diff -u
861 # - not all diff versions understand "-u"
862
863 test_cmp() {
864         $GIT_TEST_CMP "$@"
865 }
866
867 # This function can be used to schedule some commands to be run
868 # unconditionally at the end of the test to restore sanity:
869 #
870 #       test_expect_success 'test core.capslock' '
871 #               git config core.capslock true &&
872 #               test_when_finished "git config --unset core.capslock" &&
873 #               hello world
874 #       '
875 #
876 # That would be roughly equivalent to
877 #
878 #       test_expect_success 'test core.capslock' '
879 #               git config core.capslock true &&
880 #               hello world
881 #               git config --unset core.capslock
882 #       '
883 #
884 # except that the greeting and config --unset must both succeed for
885 # the test to pass.
886
887 test_when_finished () {
888         test_cleanup="{ $*
889                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
890 }
891
892 test_done () {
893         GIT_EXIT_OK=t
894         test_results_dir="$TEST_DIRECTORY/test-results"
895         mkdir -p "$test_results_dir"
896         test_results_path="$test_results_dir/${0%.sh}-$$"
897
898         echo "total $test_count" >> $test_results_path
899         echo "success $test_success" >> $test_results_path
900         echo "fixed $test_fixed" >> $test_results_path
901         echo "broken $test_broken" >> $test_results_path
902         echo "failed $test_failure" >> $test_results_path
903         echo "" >> $test_results_path
904
905         echo
906
907         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
908
909         if [ "$test_failure" = "0" ]; then
910             if [ "$test_broken" = "0" ]; then
911                 rm -rf "$remove_tmp"
912             fi
913             exit 0
914         else
915             exit 1
916         fi
917 }
918
919 emacs_generate_script () {
920         # Construct a little test script here for the benefit of the user,
921         # (who can easily run "run_emacs" to get the same emacs environment
922         # for investigating any failures).
923         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
924 #!/bin/sh
925 export PATH=$PATH
926 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
927
928 # Here's what we are using here:
929 #
930 # --no-init-file        Don't load users ~/.emacs
931 #
932 # --no-site-file        Don't load the site-wide startup stuff
933 #
934 # --directory           Ensure that the local elisp sources are found
935 #
936 # --load                Force loading of notmuch.el and test-lib.el
937
938 exec ${TEST_EMACS} --no-init-file --no-site-file \
939         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
940         --directory "$TEST_DIRECTORY" --load test-lib.el \
941         "\$@"
942 EOF
943         chmod a+x "$TMP_DIRECTORY/run_emacs"
944 }
945
946 test_emacs () {
947         # test dependencies beforehand to avoid the waiting loop below
948         missing_dependencies=
949         test_require_external_prereq dtach || missing_dependencies=1
950         test_require_external_prereq emacs || missing_dependencies=1
951         test_require_external_prereq emacsclient || missing_dependencies=1
952         test -z "$missing_dependencies" || return
953
954         if [ -z "$EMACS_SERVER" ]; then
955                 emacs_tests="$(basename $0).el"
956                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
957                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
958                 else
959                         load_emacs_tests=
960                 fi
961                 server_name="notmuch-test-suite-$$"
962                 # start a detached session with an emacs server
963                 # user's TERM is given to dtach which assumes a minimally
964                 # VT100-compatible terminal -- and emacs inherits that
965                 TERM=$ORIGINAL_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
966                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
967                                 --no-window-system \
968                                 $load_emacs_tests \
969                                 --eval '(setq server-name \"$server_name\")' \
970                                 --eval '(server-start)' \
971                                 --eval '(orphan-watchdog $$)'" || return
972                 EMACS_SERVER="$server_name"
973                 # wait until the emacs server is up
974                 until test_emacs '()' >/dev/null 2>/dev/null; do
975                         sleep 1
976                 done
977         fi
978
979         emacsclient --socket-name="$EMACS_SERVER" --eval "(progn $@)"
980 }
981
982 test_python() {
983         export LD_LIBRARY_PATH=$TEST_DIRECTORY/../lib
984         export PYTHONPATH=$TEST_DIRECTORY/../bindings/python
985
986         # Some distros (e.g. Arch Linux) ship Python 2.* as /usr/bin/python2,
987         # most others as /usr/bin/python. So first try python2, and fallback to
988         # python if python2 doesn't exist.
989         cmd=python2
990         [[ "$test_missing_external_prereq_python2_" = t ]] && cmd=python
991
992         (echo "import sys; _orig_stdout=sys.stdout; sys.stdout=open('OUTPUT', 'w')"; cat) \
993                 | $cmd -
994 }
995
996 # Creates a script that counts how much time it is executed and calls
997 # notmuch.  $notmuch_counter_command is set to the path to the
998 # generated script.  Use notmuch_counter_value() function to get the
999 # current counter value.
1000 notmuch_counter_reset () {
1001         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
1002         if [ ! -x "$notmuch_counter_command" ]; then
1003                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
1004                 cat >"$notmuch_counter_command" <<EOF || return
1005 #!/bin/sh
1006
1007 read count < "$notmuch_counter_state_path"
1008 echo \$((count + 1)) > "$notmuch_counter_state_path"
1009
1010 exec notmuch "\$@"
1011 EOF
1012                 chmod +x "$notmuch_counter_command" || return
1013         fi
1014
1015         echo 0 > "$notmuch_counter_state_path"
1016 }
1017
1018 # Returns the current notmuch counter value.
1019 notmuch_counter_value () {
1020         if [ -r "$notmuch_counter_state_path" ]; then
1021                 read count < "$notmuch_counter_state_path"
1022         else
1023                 count=0
1024         fi
1025         echo $count
1026 }
1027
1028 test_reset_state_ () {
1029         test -z "$test_init_done_" && test_init_
1030
1031         test_subtest_known_broken_=
1032         test_subtest_missing_external_prereqs_=
1033 }
1034
1035 # called once before the first subtest
1036 test_init_ () {
1037         test_init_done_=t
1038
1039         # skip all tests if there were external prerequisites missing during init
1040         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1041 }
1042
1043
1044 find_notmuch_path ()
1045 {
1046     dir="$1"
1047
1048     while [ -n "$dir" ]; do
1049         bin="$dir/notmuch"
1050         if [ -x "$bin" ]; then
1051             echo "$dir"
1052             return
1053         fi
1054         dir="$(dirname "$dir")"
1055         if [ "$dir" = "/" ]; then
1056             break
1057         fi
1058     done
1059 }
1060
1061 # Test the binaries we have just built.  The tests are kept in
1062 # test/ subdirectory and are run in 'trash directory' subdirectory.
1063 TEST_DIRECTORY=$(pwd)
1064 if test -n "$valgrind"
1065 then
1066         make_symlink () {
1067                 test -h "$2" &&
1068                 test "$1" = "$(readlink "$2")" || {
1069                         # be super paranoid
1070                         if mkdir "$2".lock
1071                         then
1072                                 rm -f "$2" &&
1073                                 ln -s "$1" "$2" &&
1074                                 rm -r "$2".lock
1075                         else
1076                                 while test -d "$2".lock
1077                                 do
1078                                         say "Waiting for lock on $2."
1079                                         sleep 1
1080                                 done
1081                         fi
1082                 }
1083         }
1084
1085         make_valgrind_symlink () {
1086                 # handle only executables
1087                 test -x "$1" || return
1088
1089                 base=$(basename "$1")
1090                 symlink_target=$TEST_DIRECTORY/../$base
1091                 # do not override scripts
1092                 if test -x "$symlink_target" &&
1093                     test ! -d "$symlink_target" &&
1094                     test "#!" != "$(head -c 2 < "$symlink_target")"
1095                 then
1096                         symlink_target=$TEST_DIRECTORY/valgrind.sh
1097                 fi
1098                 case "$base" in
1099                 *.sh|*.perl)
1100                         symlink_target=$TEST_DIRECTORY/unprocessed-script
1101                 esac
1102                 # create the link, or replace it if it is out of date
1103                 make_symlink "$symlink_target" "$GIT_VALGRIND/bin/$base" || exit
1104         }
1105
1106         # override notmuch executable in TEST_DIRECTORY/..
1107         GIT_VALGRIND=$TEST_DIRECTORY/valgrind
1108         mkdir -p "$GIT_VALGRIND"/bin
1109         make_valgrind_symlink $TEST_DIRECTORY/../notmuch
1110         OLDIFS=$IFS
1111         IFS=:
1112         for path in $PATH
1113         do
1114                 ls "$path"/notmuch 2> /dev/null |
1115                 while read file
1116                 do
1117                         make_valgrind_symlink "$file"
1118                 done
1119         done
1120         IFS=$OLDIFS
1121         PATH=$GIT_VALGRIND/bin:$PATH
1122         GIT_EXEC_PATH=$GIT_VALGRIND/bin
1123         export GIT_VALGRIND
1124 else # normal case
1125         notmuch_path=`find_notmuch_path "$TEST_DIRECTORY"`
1126         test -n "$notmuch_path" && PATH="$notmuch_path:$PATH"
1127 fi
1128 export PATH
1129
1130 # Test repository
1131 test="tmp.$(basename "$0" .sh)"
1132 test -n "$root" && test="$root/$test"
1133 case "$test" in
1134 /*) TMP_DIRECTORY="$test" ;;
1135  *) TMP_DIRECTORY="$TEST_DIRECTORY/$test" ;;
1136 esac
1137 test ! -z "$debug" || remove_tmp=$TMP_DIRECTORY
1138 rm -fr "$test" || {
1139         GIT_EXIT_OK=t
1140         echo >&5 "FATAL: Cannot prepare test area"
1141         exit 1
1142 }
1143
1144 # A temporary home directory is needed by at least:
1145 # - emacs/"Sending a message via (fake) SMTP"
1146 # - emacs/"Reply within emacs"
1147 # - crypto/emacs_deliver_message
1148 export HOME="${TMP_DIRECTORY}/home"
1149 mkdir -p "${HOME}"
1150
1151 MAIL_DIR="${TMP_DIRECTORY}/mail"
1152 export GNUPGHOME="${TMP_DIRECTORY}/gnupg"
1153 export NOTMUCH_CONFIG="${TMP_DIRECTORY}/notmuch-config"
1154
1155 mkdir -p "${test}"
1156 mkdir -p "${MAIL_DIR}"
1157
1158 cat <<EOF >"${NOTMUCH_CONFIG}"
1159 [database]
1160 path=${MAIL_DIR}
1161
1162 [user]
1163 name=Notmuch Test Suite
1164 primary_email=test_suite@notmuchmail.org
1165 other_email=test_suite_other@notmuchmail.org;test_suite@otherdomain.org
1166 EOF
1167
1168 emacs_generate_script
1169
1170
1171 # Use -P to resolve symlinks in our working directory so that the cwd
1172 # in subprocesses like git equals our $PWD (for pathname comparisons).
1173 cd -P "$test" || error "Cannot setup test environment"
1174
1175 if test "$verbose" = "t"
1176 then
1177         exec 4>&2 3>&1
1178 else
1179         exec 4>test.output 3>&4
1180 fi
1181
1182 this_test=${0##*/}
1183 for skp in $NOTMUCH_SKIP_TESTS
1184 do
1185         to_skip=
1186         for skp in $NOTMUCH_SKIP_TESTS
1187         do
1188                 case "$this_test" in
1189                 $skp)
1190                         to_skip=t
1191                 esac
1192         done
1193         case "$to_skip" in
1194         t)
1195                 say_color skip >&3 "skipping test $this_test altogether"
1196                 say_color skip "skip all tests in $this_test"
1197                 test_done
1198         esac
1199 done
1200
1201 # Provide an implementation of the 'yes' utility
1202 yes () {
1203         if test $# = 0
1204         then
1205                 y=y
1206         else
1207                 y="$*"
1208         fi
1209
1210         while echo "$y"
1211         do
1212                 :
1213         done
1214 }
1215
1216 # Fix some commands on Windows
1217 case $(uname -s) in
1218 *MINGW*)
1219         # Windows has its own (incompatible) sort and find
1220         sort () {
1221                 /usr/bin/sort "$@"
1222         }
1223         find () {
1224                 /usr/bin/find "$@"
1225         }
1226         sum () {
1227                 md5sum "$@"
1228         }
1229         # git sees Windows-style pwd
1230         pwd () {
1231                 builtin pwd -W
1232         }
1233         # no POSIX permissions
1234         # backslashes in pathspec are converted to '/'
1235         # exec does not inherit the PID
1236         ;;
1237 *)
1238         test_set_prereq POSIXPERM
1239         test_set_prereq BSLASHPSPEC
1240         test_set_prereq EXECKEEPSPID
1241         ;;
1242 esac
1243
1244 test -z "$NO_PERL" && test_set_prereq PERL
1245 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1246
1247 # test whether the filesystem supports symbolic links
1248 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1249 rm -f y
1250
1251 # declare prerequisites for external binaries used in tests
1252 test_declare_external_prereq dtach
1253 test_declare_external_prereq emacs
1254 test_declare_external_prereq emacsclient
1255 test_declare_external_prereq gdb
1256 test_declare_external_prereq gpg
1257 test_declare_external_prereq python
1258 test_declare_external_prereq python2