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