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